Java与javascript正则表达式匹配

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相同吗?

anu*_*ava 5

这是因为在 Java 中Pattern#matchesORString#matches期望您匹配完整的输入字符串而不仅仅是其中的一部分。

另一方面,String#match正如您在示例中看到的那样,Javascript可以部分匹配输入。

  • 在 Java 中,它需要这样做:`Pattern.matches(".*?q.*", "Iraq");` 或者更好地使用`Pattern#find()` 方法,该方法用于部分匹配。 (3认同)
  • 顺便说一句:Python 也有 `re.match()` 和 `re.search()`。第一个 _match_es 整个字符串从头到尾,第二个 _search_es 如果找到字符串 (2认同)

Psh*_*emo 5

在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)