我读过 the manual ,最后有一个练习:
Use a backreference to write an expression that will match a person's name only if that person's first name and last name are the same.
我已经编写了下一个程序 http://pastebin.com/YkuUuP5M
但是当我编译它时,出现错误:
PersonName.java:18: illegal escape character
p = Pattern.compile("([A-Z][a-zA-Z]+)\s+\1");
^
如果我这样重写 18 行:
pattern = Pattern.compile(console.readLine("%nEnter your regex: "));
然后在控制台中写入模式,然后程序就可以正常运行了。为什么我不能使用第一个程序案例中的模式,有什么办法可以解决这个问题吗?
最佳答案
你想把这个文本变成一个字符串:
([A-Z][a-zA-Z]+)\s+\1
但是,Java 源代码中的字符串文字 中的\
是用于转义的字符(例如,“\t”代表制表符)。因此,您需要在字符串文字中使用“\”以在结果字符串中以单个反斜杠结尾。所以你想要:
"([A-Z][a-zA-Z]+)\\s+\\1"
请注意,这里没有任何特定于正则表达式的内容。 任何时候您想要在 Java 字符串文字中表达包含反斜杠的字符串时,您都需要对该反斜杠进行转义。正则表达式和 Windows 文件名只是最常见的情况。
关于java - Java正则表达式中的非法转义字符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8154628/