簡體   English   中英

使用正則表達式捕獲字符串中的所有數字而不會拆分

[英]Capturing all numbers from string with regular expressions without splitting

我需要使用一些正則表達式來解析更復雜的文本,並且我想知道是否可以使用非捕獲組來匹配多個數字並提取它們嗎? 我知道我可以匹配用空格分隔的數字,然后將它們按空格分隔,但是即使我不知道它們的數量,我也希望將所有數字分成不同的組。

下面的示例僅匹配最后一個數字:

----Start----
--------
i 0 11 22 4444 
i 1 4444
--------
i 0 34 56
i 1 56

但我想得到:

----Start----
--------
i 0 11 22 4444 
i 1 11
i 2 22
i 3 4444
--------
i 0 34 56
i 1 34
i 2 56

這是我的代碼:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("----Start----");

        Pattern compile = Pattern.compile("(?:(\\d+)\\s*)+");
        String s = "11 22 4444 mam a 34 56";

        Matcher matcher = compile.matcher(s);
        while(matcher.find()){
            System.out.println("--------");
            for (int i=0;i<matcher.groupCount()+1;i++){
                System.out.println("i " + i = " " + matcher.group(i));
            }
        }
    }
}

您無法做到這一點,因此請拆分匹配項。 僅存儲捕獲組的最后一個值。 據我所知,只有.NET正則表達式會保存所有以前的捕獲。

    matcher = compile.matcher(s);
    Pattern subCompile = Pattern.compile("(\\d+)");
    while (matcher.find()) {
        System.out.println("--------");
        Matcher subMatcher = subCompile.matcher(matcher.group());
        while (subMatcher.find())
            System.out.println(subMatcher.group());
    }

也可以。 輸出:

--------
11
22
4444
--------
34
56

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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