正则表达式的转义字符在编译器中无法通过的问题
代码如下:
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
Pattern p = Pattern.compile("(?i)((^[aeiou])|(\s+[aeiou]))\w+?[aeiou]\b");
Matcher m = p.matcher("Arline ate eight apples and one orange while Anita hadn't any");
while(m.find()) {
System.out.println("Match \"" + m.group() + "\" at positions " +
m.start() + "-" + (m.end() - 1));
}
}
}
在此例中,用Jcreator编译,提示"(?i)((^[aeiou])|(\s+[aeiou]))\w+?[aeiou]\b"中的\s和\w为非法转义字符~
请问是编译器的问题还是其他问题~?应该如何解决~?
另,如果把代码改为:
public class Test {
public static void main(String[] args) {
for(String tmp:args) {
Pattern p = Pattern.compile(tmp);
Matcher m = p.matcher("Arline ate eight apples and one orange while Anita hadn't any");
while(m.find()) {
System.out.println("Match \"" + m.group() + "\" at positions " +
m.start() + "-" + (m.end() - 1));
}
}
}
}
编译后,在命令提示符输入java Test a|b 得到如下错误信息:
'b'不是内部或外部命令,也不是可运行的程序或批处理文件。
偶觉得应该是|未被识别~~
请问这是为什么咯~?
谢谢~~
------解决方案--------------------to question 1:
--> 正则式的转义符在java里面是要用两个“\\”来表式,所以应改成:
Pattern p = Pattern.compile("(?i)((^[aeiou]) |(\\s+[aeiou]))\\w+?[aeiou]\\b");
------解决方案--------------------to question 2:
-->LZ要从键盘上输入正则式,必须加上“”。LZ用java Test "a ¦b "就可以了