正则表达式似乎没问题,因为第一行的行正确地用“helloworld”替换了子串,但后者的相同表达式不匹配,因为我看不到“whynothelloworld”。在控制台上
System.out.println(current_tag.replaceAll("^[01][r]\\s", "helloworld"));
if (Pattern.matches("^[01][r]\\s", current_tag)) { System.out.println("whynothelloworld?");}
答案 0 :(得分:15)
Pattern.matches()
期望整个字符串匹配,而不仅仅是子字符串。
使用正则表达式匹配器对象的.find()
方法:
Pattern regex = Pattern.compile("^[01]r\\s");
Matcher regexMatcher = regex.matcher(current_tag);
foundMatch = regexMatcher.find();
答案 1 :(得分:-3)
它再次无法匹配,因为您只是将其替换为“helloworld”。
编辑:抱歉,我忘了这是如何运作的。