java正则表达式查找具有特殊字符的精确单词

java正则表达式查找具有特殊字符的精确单词,java,regex,string,expression,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 $SEBGI is there there is $SE. there is SE again 请帮助。使用: String

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

$SEBGI is there
there is $SE.
there is SE again
输出应如下所示:

FALSE
TRUE
FALSE
我有下面的正则表达式

String patternStr =  "(?i)\\b"+Pattern.quote("$SE")+"\\b";
但是对于所有的句子,它都返回
FALSE

$SEBGI is there
there is $SE.
there is SE again
请帮助。

使用:

String example = "the charseq test";
String pattern = "(?i).*(^|\\s)" + Pattern.quote("charseq") + "($|\\s).*";
boolean matches = example.matches(pattern);

你真的不需要这个词的边界

我认为最简单的解决方案是再次使用一系列非单词“$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
注:

  • 我没有使用
    模式。quote
    ,因为它只有一个“有问题的”字符($),所以我只是对它进行了转义
  • 我没有使用look behinds或look aheads,因为在这种情况下它们并不真正需要
  • 我没有使用分组,因为您没有尝试检索任何内容,只是为了检查
    字符串
    是否包含与
    模式
    匹配的内容
  • 我使用了
    模式。不区分大小写
    标志,因为您似乎需要它(请参阅您的
    (?I)
    标志-同样的事情)

您始终可以使用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;
boolean str_beg=Pattern.matches(“^\\$SE\\s,”);
布尔str_mid=Pattern.matches(“\\s\\$SE\\s”,”);
布尔str_end=Pattern.matches(“\\s\\$SE$”,);
布尔str_all=Pattern.matches(“^\\$SE$”,);
布尔匹配=str|u beg | str|u mid | str|u end | str|u all;

显示您的代码,否则我们看不出您做错了什么。另外,您的需求不够明确。应该<代码> Abs$fo< <代码>是代码>真的< /代码>还是<代码> false < /代码>?请确切地定义你想考虑的单词边界。内置的
\b
仅适用于纯字母数字的“单词”。您的“单词”末尾是否可能有非字母数字字符(如
$SE$
)?谢谢Mena,它适用于此情况。我已经更新了我的问题并添加了详细信息。你能给我复习和指导吗?@AnkurRaiyani这不是它的工作原理。你的新问题看起来不错,但你不能彻底改变原来的问题,也不能指望回答问题的人也更新他们的答案。我认为你应该回到上一个问题,如果有必要,把它关闭(或者标记为“已回答”),然后问一个新问题,这样每个人都有机会公平、清晰地回答这个新问题。好的,我已经将你的问题标记为答案,并将创建新问题