我需要匹配一行字符串里面所有的 ${} 占位符,使用的正则表达式为
\$\{(.*?)\}
测试字符串为:
hello, ${name}. Your level is ${level}
我用 OSChina 的在线正则表达式测试工具 http://tool.oschina.net/regex/ 进行测试,可以正确匹配到两个占位符。
但是我在 Java 里面就不能匹配到。
Pattern pattern = Pattern.compile("\\$\\{(.*?)\\}");
String test = "hello, ${name}. Your level is ${level}";
Matcher matcher = pattern.matcher(test);
System.out.println(matcher.matches()); // 输出 false
求教这是怎么回事~~懵逼了一早上
1
c4f36e5766583218 2019-04-30 12:26:49 +08:00
http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/regex/Matcher.html#matches()
当且仅当整个区域序列匹配此匹配器的模式时才返回 true。 |
2
iffi 2019-04-30 12:32:39 +08:00
这样子来
```public static void main(String[] args) { Pattern pattern = Pattern.compile("\\$\\{(.*?)\\}"); String test = "hello, ${name}. Your level is ${level}"; Matcher matcher = pattern.matcher(test); while (matcher.find()) { System.out.println(matcher.group()); } } ``` |
3
Defined 2019-04-30 13:49:51 +08:00
import java.util.regex.Matcher;
import java.util.regex.Pattern; final String regex = "\\$\\{(.*?)\\}"; final String string = "hello, ${name}. Your level is ${level}\n"; final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); final Matcher matcher = pattern.matcher(string); while (matcher.find()) { System.out.println("Full match: " + matcher.group(0)); for (int i = 1; i <= matcher.groupCount(); i++) { System.out.println("Group " + i + ": " + matcher.group(i)); } } |
4
mooncakejs 2019-04-30 14:10:01 +08:00
java 坑爹处就是 matches 从头匹配到尾
|