我需要在"$SE"
关键字中搜索以下句子。
$SEBGI is there
there is $SE.
there is SE again
输出应如下:
FALSE
TRUE
FALSE
我遵循正则表达式。
String patternStr = "(?i)\\b"+Pattern.quote("$SE")+"\\b";
但它会为所有句子返回FALSE
。
请帮忙。
答案 0 :(得分:2)
你真的不需要这个词边界。
我认为最简单的解决方案是使用一系列非单词,“$ SE”和非单词。
例如:
String first = "$SEBGI is there";
String second = "there is $SE.";
String third = "there is SE again";
Pattern pattern = Pattern.compile("\\W\\$SE\\W", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(first);
System.out.println(matcher.find());
matcher = pattern.matcher(second);
System.out.println(matcher.find());
matcher = pattern.matcher(third);
System.out.println(matcher.find());
输出:
false
true
false
注意:
Pattern.quote
,因为它只是一个“有问题”的字符( $ ),所以我只是将其转义。 String
是否包含Pattern
的匹配项。Pattern.CASE_INSENSITIVE
标志,因为您似乎需要它(请参阅(?i)
标志 - 同样的事情)。答案 1 :(得分:0)
使用:
String example = "the charseq test";
String pattern = "(?i).*(^|\\s)" + Pattern.quote("charseq") + "($|\\s).*";
boolean matches = example.matches(pattern);
答案 2 :(得分:0)
您始终可以使用4个单独的表达式:
boolean str_beg = Pattern.matches("^\\$SE\\s", <input_str>);
boolean str_mid = Pattern.matches("\\s\\$SE\\s", <input_str>);
boolean str_end = Pattern.matches("\\s\\$SE$", <input_str>);
boolean str_all = Pattern.matches("^\\$SE$", <input_str>);
boolean matches = str_beg || str_mid || str_end || str_all;