本文介绍了Java匹配与JavaScript匹配之间的结果差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我做一个简单的测试时,我正在用Java复习正则表达式
I was brushing up on my regular expressions in java when I did a simple test
Pattern.matches("q", "Iraq"); //false
"Iraq".matches("q"); //false
但是在JavaScript中
But in JavaScript
/q/.test("Iraq"); //true
"Iraq".match("q"); //["q"] (which is truthy)
这是怎么回事?我可以将我的Java正则表达式模式"q"设置为行为与JavaScript相同?
What is going on here? And can I make my java regex pattern "q" behave the same as JavaScript?
推荐答案
在JavaScript match
中返回与使用的正则表达式匹配的子字符串.在Java中, matches
检查整个字符串是否与正则表达式匹配.
In JavaScript match
returns substrings which matches used regex. In Java matches
checks if entire string matches regex.
如果要查找与正则表达式匹配的子字符串,请使用Pattern和Matcher类,如
If you want to find substrings that match regex use Pattern and Matcher classes like
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");
}
这篇关于Java匹配与JavaScript匹配之间的结果差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!