简体   繁体   English

Java匹配正则表达式并提取组oneliner

[英]Java match regex and extract group oneliner

I have a simple regex like 我有一个简单的正则表达式

%(\d+)\$@[_a-zA-Z0-9]+@

I don't want to write 我不想写

Matcher m = Pattern.compile(myRegex).matcher(myText);
if (m.matches())
   // do something with m.group(1);

What I would really like to do is to have a one liner like 我真正想做的就是拥有一个像

// do something with
Pattern.compile(myRegex).matcher(myText).match().group(1);

Do you know a good way to do that in Java (I'm using Java 7 but perhaps something changed in 8)? 您知道在Java中执行此操作的好方法吗(我使用的是Java 7,但也许在8中有所更改)?

As of Java 9, you can stream match results and grab the first group of the first result: 从Java 9开始,您可以流式传输匹配结果并获取第一个结果的第一组:

String result = Pattern.compile(myRegex)
        .matcher(myText)
        .results()
        .map(m -> m.group(1))
        .findFirst()
        .orElse(null);

Here is one : 这是一个:

Integer.valueOf(Pattern.compile(myRegex).matcher(myText).matches() ? 
        Pattern.compile(myRegex).matcher(myText).group(1) : "0");
//-----------------------------------------Not match---------^

Edit 编辑

You ca also use : 您也可以使用:

Matcher m;
Integer.valueOf((m = Pattern.compile(myRegex).matcher(myText)).matches() ? 
        m.group(1) : "0");

create a static matcher: 创建一个静态匹配器:

private static Matcher matcher = Pattern.compile(myRegex).matcher("");

and use it this way: 并以这种方式使用它:

public String match(String myText, String defaultValue) {
  matcher.reset(myText);
  return matcher.matches() ? matcher.group(1) : defaultValue;
}

This is the most efficient way of using regexs (as far as I know). 这是使用正则表达式的最有效方法(据我所知)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM