模式前瞻

发布于 2024-12-05 06:08:42 字数 373 浏览 5 评论 0原文

Pattern p = Pattern.compile("(ma)|([a-zA-Z_]+)");
Matcher m = p.matcher("ma");
m.find();
System.out.println("1 " + m.group(1) + ""); //ma
System.out.println("2 " + m.group(2)); // null
Matcher m = p.matcher("mad");
m.find();
System.out.println("1 " + m.group(1) + ""); //ma
System.out.println("2 " + m.group(2)); // null

但我需要字符串“mad”位于第二组中。

Pattern p = Pattern.compile("(ma)|([a-zA-Z_]+)");
Matcher m = p.matcher("ma");
m.find();
System.out.println("1 " + m.group(1) + ""); //ma
System.out.println("2 " + m.group(2)); // null
Matcher m = p.matcher("mad");
m.find();
System.out.println("1 " + m.group(1) + ""); //ma
System.out.println("2 " + m.group(2)); // null

But I need that the string "mad" would be in the 2nd group.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泪冰清 2024-12-12 06:08:42

我认为您正在寻找的是这样的:

(ma(?!d))|([a-zA-Z_]+)

来自“perldoc perlre”:

“(?!模式)”
零宽度负前瞻断言。为了
例子
“/foo(?!bar)/” 匹配任何出现的“foo”
不是
后跟“栏”。

我唯一不确定的是Java是否支持这种语法,但我认为它支持。

I think what you are looking for is something like:

(ma(?!d))|([a-zA-Z_]+)

from "perldoc perlre":

"(?!pattern)"
A zero-width negative look-ahead assertion. For
example
"/foo(?!bar)/" matches any occurrence of "foo" that
isn't
followed by "bar".

the only thing I'm not sure about is whether Java supports this syntax, but I think it does.

终止放荡 2024-12-12 06:08:42

如果您使用 matches 而不是 find,它会尝试将整个字符串与该模式进行匹配,这只能通过将 mad 放入第二组:

import java.util.regex.*;

public class Test {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("(ma)|([a-zA-Z_]+)");
        Matcher m = p.matcher("ma"); 
        m.matches();
        System.out.println("1 " + m.group(1)); // ma
        System.out.println("2 " + m.group(2)); // null
        m = p.matcher("mad"); 
        m.matches();
        System.out.println("1 " + m.group(1)); // null
        System.out.println("2 " + m.group(2)); // mad
    }
}

If you use matches instead of find, it will try to match the entire string against that pattern, which it can only do by putting mad in the second group:

import java.util.regex.*;

public class Test {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("(ma)|([a-zA-Z_]+)");
        Matcher m = p.matcher("ma"); 
        m.matches();
        System.out.println("1 " + m.group(1)); // ma
        System.out.println("2 " + m.group(2)); // null
        m = p.matcher("mad"); 
        m.matches();
        System.out.println("1 " + m.group(1)); // null
        System.out.println("2 " + m.group(2)); // mad
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文