0

我需要"$SE"为以下句子搜索关键字。

$SEBGI is there
there is $SE.
there is SE again

输出应如下所示:

FALSE
TRUE
FALSE

我有以下正则表达式。

String patternStr =  "(?i)\\b"+Pattern.quote("$SE")+"\\b";

但它返回FALSE所有句子。

请帮忙。

4

3 回答 3

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)标志-同样的事情)。
于 2013-08-02T15:54:28.110 回答
0

利用:

String example = "the charseq test";
String pattern = "(?i).*(^|\\s)" + Pattern.quote("charseq") + "($|\\s).*";
boolean matches = example.matches(pattern);
于 2013-08-02T15:37:59.367 回答
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;
于 2013-08-02T16:05:33.370 回答