我在 Oracle 文档中读到 \z
表示输入结束。但编译器会抛出错误。
当 java 是最后一个单词时,我需要在文本中找到单词“java”。有什么建议如何处理吗?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Why {
public static void main(String[] args) {
String language = "java";
String text = "I'm fan of java";
Pattern p = Pattern.compile("\\s" + language + "[\\W|\\z]");
Matcher m = p.matcher(text);
System.out.println(m.find()); // <-------------- Exception
}
}
// Exception in thread "main" java.util.regex.PatternSyntaxException:
// Illegal/unsupported escape sequence near index 11 \sjava[\W|\z]
最佳答案
[...]
定义一个字符类,您可以在其中定义字符。 \z
是一个 anchor ,一个零宽度断言。所有零宽度断言 - \A
, \b
, \G
, ^
, $
- 当放入字符类中时,不要保留它们的“特殊”含义。
您收到的错误是由于 the fact that
It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language.
您似乎想要匹配前面有空格或字符串开头的单词,或者后面有非单词、数字或字符串结尾的单词。我建议使用
Pattern p = Pattern.compile("(?<!\\S)" + Pattern.quote(language) + "(?![^\\W\\d])");
(?<!\\S)
是一个负向后查找,仅匹配紧接在空格或字符串开头之前的位置。 (?![^\\W\\d])
是一个负向先行,如果下一个字符不是非单词字符或不是数字(因此可以是数字、非单词或字符串结尾),则匹配失败。
请参阅regex demo .
关于java - 为什么正则表达式的\z 对我不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46351488/