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/6521992/

相关文章:

java - Linux下最大线程数

java - 用破折号替换前导零直到小数点

javascript - 使用 Javascript 从文本区域中删除 BBcode

java swing并发在JTextArea中循环显示文本

java - 最佳实践 : instance variables filling over time

javascript - 正则表达式限制小数点后两位

javascript - 如何使用 JavaScript 获取输入字段中光标下的字符串

regex - 使用 awk 查找和替换通过 find 找到的文件中的字符串

java - 使用 JDBC 绑定(bind)函数调用

java - jsp session 中的类型转换错误