java - Pattern.matches不起作用,而replaceAll起作用

标签 java regex

正则表达式似乎还可以,因为第一行用“ 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/59262802/

相关文章:

regex - 在 R 中使用正则表达式捕获部分字符串

javascript - 如何在 javascript 中使用正则表达式获取文本

java - Java 是否允许在编译时进行不变性检查?

java - 无法使用 <jsp :useBean>: "Bean cannot be resolved to a type"

java - junit/mockito 中的断言不正确

Java未初始化变量错误

iphone - NSRegularExpression 用于从字符串中检索数字

php - 用于确定字符串特定特征的正则表达式(即扑克牌)

.csv 格式的正则表达式和定位项

java - 如何写入没有属性名称的 JSON 值