[英]Java match regex and extract group oneliner
我有一个简单的正则表达式
%(\d+)\$@[_a-zA-Z0-9]+@
我不想写
Matcher m = Pattern.compile(myRegex).matcher(myText);
if (m.matches())
// do something with m.group(1);
我真正想做的就是拥有一个像
// do something with
Pattern.compile(myRegex).matcher(myText).match().group(1);
您知道在Java中执行此操作的好方法吗(我使用的是Java 7,但也许在8中有所更改)?
从Java 9开始,您可以流式传输匹配结果并获取第一个结果的第一组:
String result = Pattern.compile(myRegex)
.matcher(myText)
.results()
.map(m -> m.group(1))
.findFirst()
.orElse(null);
这是一个:
Integer.valueOf(Pattern.compile(myRegex).matcher(myText).matches() ?
Pattern.compile(myRegex).matcher(myText).group(1) : "0");
//-----------------------------------------Not match---------^
编辑
您也可以使用:
Matcher m;
Integer.valueOf((m = Pattern.compile(myRegex).matcher(myText)).matches() ?
m.group(1) : "0");
创建一个静态匹配器:
private static Matcher matcher = Pattern.compile(myRegex).matcher("");
并以这种方式使用它:
public String match(String myText, String defaultValue) {
matcher.reset(myText);
return matcher.matches() ? matcher.group(1) : defaultValue;
}
这是使用正则表达式的最有效方法(据我所知)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.