模式前瞻
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您正在寻找的是这样的:
来自“perldoc perlre”:
我唯一不确定的是Java是否支持这种语法,但我认为它支持。
I think what you are looking for is something like:
from "perldoc perlre":
the only thing I'm not sure about is whether Java supports this syntax, but I think it does.
如果您使用
matches
而不是find
,它会尝试将整个字符串与该模式进行匹配,这只能通过将mad
放入第二组:If you use
matches
instead offind
, it will try to match the entire string against that pattern, which it can only do by puttingmad
in the second group: