簡體   English   中英

Java匹配正則表達式並提取組oneliner

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM