java Regular Expression用于查找带有特殊字符的精确单词

时间:2013-08-02 15:29:33

标签: java regex string expression

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

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

输出应如下:

FALSE
TRUE
FALSE

我遵循正则表达式。

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

但它会为所有句子返回FALSE

请帮忙。

3 个答案:

答案 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;