jer*_*mel 6 javascript java regex
当我做一个简单的测试时,我正在刷java中的正则表达式
Pattern.matches("q", "Iraq"); //false
"Iraq".matches("q"); //false
Run Code Online (Sandbox Code Playgroud)
但在javascript中
/q/.test("Iraq"); //true
"Iraq".match("q"); //["q"] (which is truthy)
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?我可以使我的java正则表达式模式"q"表现与javascript相同吗?
这是因为在 Java 中Pattern#matchesORString#matches期望您匹配完整的输入字符串而不仅仅是其中的一部分。
另一方面,String#match正如您在示例中看到的那样,Javascript可以部分匹配输入。
在JavaScript中match返回匹配使用的正则表达式的子字符串.在Java中matches检查整个字符串是否与正则表达式匹配.
如果你想找到匹配正则表达式的子串,请使用Pattern和Matcher类
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(yourData);
while(m.find()){
m.group();//this will return current match in each iteration
//you can also use other groups here using their indexes
m.group(2);
//or names (?<groupName>...)
m.group("groupName");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6614 次 |
| 最近记录: |