gpt4 book ai didi

java - Java 匹配与 JavaScript 匹配之间的结果差异

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:55 25 4
gpt4 key购买 nike

当我做一个简单的测试时,我正在复习我在 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 相同?

最佳答案

在 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");
}

关于java - Java 匹配与 JavaScript 匹配之间的结果差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21883629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com