正则表达式似乎没问题,因为第一行正确地将子字符串替换为“helloworld”,但相同的表达式在后者中不匹配,因为我看不到“whynothelloworld?”在控制台上
System.out.println(current_tag.replaceAll("^[01][r]\\s", "helloworld"));
if (Pattern.matches("^[01][r]\\s", current_tag)) { System.out.println("whynothelloworld?");}
最佳答案
Pattern.matches()
期望匹配整个 字符串,而不仅仅是一个子字符串。
改为使用正则表达式匹配器对象的 .find()
方法:
Pattern regex = Pattern.compile("^[01]r\\s");
Matcher regexMatcher = regex.matcher(current_tag);
foundMatch = regexMatcher.find();
关于java - Pattern.matches 不起作用,而 replaceAll 起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6521992/