用于查找后面或前面有特殊字符的单词位置的正则表达式

regular expression for finding a word position followed or preceded by special character

我想找到一个单词在一个长字符串中的位置。该词的前面或后面可以是特殊字符,但不能是字母数字字符。所以如果我搜索德国并且字符串包含德国!!或 $germany 或 $germany)( 或 germany 我想要它的位置。我如何为此编写正则表达式。我试过这个 (?i)(?<=^|[^a-z])germany(?=$|[ ^a-z]) 但它不起作用。

String s="(?i)(?<=^|[^a-z])germany(?=$|[^a-z])";
Pattern p= Pattern.compile("(?i)(?<=^|[^a-z])cat(?=$|[^a-z])");
Matcher m=p.matcher(" germany@ is germany");
System.out.println(m.matches());

return 每次都是假的。你能建议一个正确的方法吗?我想找到这样的词并替换它们。

  1. 您需要使用 matcherobject.find() 方法才能找到匹配的子字符串。 matches 方法将尝试根据整个输入字符串检查正则表达式。

  2. Pattern p= Pattern.compile("(?i)(?<=^|[^A-Z0-9a-z])germany(?=$|[^A-Z0-9a-z])");

对于非字母数字,您还需要在否定字符 class.

中使用 A-Z0-9
ArrayList<Integer> positions = new ArrayList();
String s = "germany@ is germany";
Pattern p= Pattern.compile("(?i)(?<=^|[^a-zA-Z\d])(g)ermany(?=$|[^a-zA-Z\d])");
Matcher m=p.matcher(s);
while(m.find())
{
positions.add(m.start());
}
System.out.println(positions);

输出:

[0, 12]

虽然上面的答案是正确的,但是使用这个正则表达式可以提高效率

        Pattern p = Pattern.compile("(?<![^\W_])" + string + "(?![^\W_])");

你的工作应该花更少的时间