当我做一个简单的测试时,我正在刷新我在java中的正则表达式
Pattern.matches("q", "Iraq"); //false
"Iraq".matches("q"); //false
但是在javascript中
/q/.test("Iraq"); //true
"Iraq".match("q"); //["q"] (which is truthy)
这里发生了什么?我可以使我的java正则表达式模式“q”表现与javascript相同吗?
答案 0 :(得分: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");
}
答案 1 :(得分:4)
这是因为在Java Pattern#matches
或String#matches
期望您匹配完整的输入字符串而不仅仅是它的一部分。
另一方面,Javascript&#39; String#match
可以部分匹配输入,因为您在示例中也会看到。
答案 2 :(得分:3)
在Java中,如果整个输入字符串与给定模式匹配,则Pattern.matches返回true。这相当于说,在你的例子中,“iraq”应匹配“^ q $”,这显然不匹配。
这是来自Java的Pattern Javadoc:
public boolean matches()
尝试将整个区域与模式匹配。如果匹配成功,则可以通过start,end和group方法获得更多信息。
返回:当且仅当整个区域序列与此匹配器的模式
匹配时才返回true
如果您只想测试字符串的一部分,请在正则表达式的开头和结尾添加.*
,例如Pattern.match("iraq", ".*q.*")
。