繁体   English   中英

Java正则表达式:匹配多个单词边界

[英]Java regex: match multiple word boundaries

我想在文本中匹配几个单词。 有以下内容:

if ( Pattern.matches(".*\\b" + placeSub.toLowerCase() + "\\b" + placeSup.toLowerCase() + "\\b.*", sourceText.toLowerCase()) ) {
    System.out.println( String.format("Matched %s on %s", placeSub, placeSup) );        
}

变量placeSubplaceSupsourceText是动态的(运行时)。

上面的代码不起作用(不匹配)。 但是,以下匹配项:

if ( Pattern.matches(".*\\b" + placeSub.toLowerCase() + "\\s" + placeSup.toLowerCase() + "\\b.*", sourceText.toLowerCase()) ) {
   System.out.println( String.format("Matched %s on %s", placeSub, placeSup) ); 
}

为什么文本可以匹配\\\\s而不匹配\\\\b

输入示例:

  1. placeSub: South

  2. placeSup: Sudan

  3. sourceText: tens of thousands of people have fled fierce fighting in south sudan's northern unity state

您实际上应该使用:

Pattern.matches(
   ".*?\\b" + placeSub.toLowerCase() + "\\b\\W+\\b" + placeSup.toLowerCase() + "\\b.*",
   sourceText.toLowerCase())

它将转换为:

/.*?\bsouth\b\W+\bsudan\b.*/i

在这里查看正则表达式演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM