*或+修饰符内的组捕获

时间:2019-02-10 10:05:36

标签: java regex capturing-group

在使用+或*修饰符的情况下捕获组如何工作?

JDK 8

java.util.regex.Matcher

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

public class Regex 
{
static public String[] matchedParts(String regex, String text)
    {
        Pattern p = Pattern.compile(regex);

        Matcher m = p.matcher(text);

        Vector<String> matchedParts = new Vector<String>(100);
        try
        {
            while (m.find())
            {
                for (int i = 1; i <= m.groupCount(); i++)
                {
                    matchedParts.add(m.group(i));
                }
            }
        }
        catch (IndexOutOfBoundsException e)
        {
            matchedParts.add(m.group(0));
        }
        return matchedParts.toArray(new String[0]);
    }
}

public static void main(String[] args) 
{
    String toto[] = org.easy.support.text.Regex.matchedParts("([^,]+,)+", "a,bb,ccc,dddd,eeeee,ffffff,ggggggg,");
    for (int i = 0; i < toto.length; i++)
    {
         System.out.println("\"" + toto[i] + "\"");
    }
}

我希望: “一种,” “ bb” “抄送” “ dddd” “ eeeee” “ ffffff” “ ggggggg”

我得到

“ ggggggg”

如果我将“([[^,] +,)+”替换为“([^,] +,)([^,] +,)([^,] +,)([^,] +, )([^,] +,)([^,] +,)([^,] +,)“,可以正常使用。

欢呼

0 个答案:

没有答案