-2

我有一个类似的字符串:

++ name1
description:asdfmkdfkmfkskfsaf \n

++ name2
description:asdfmkdfkmfkskfsaf \n

++ name3 description:asdfmkdfkmfkskfsaf

我想将其提取到如下组中:

group1:
name1
description:asdfmkdfkmfkskfsaf

group2:
name2
description:asdfmkdfkmfkskfsaf

group3:
name3
description:asdfmkdfkmfkskfsaf

如何用正则表达式做到这一点?

4

1 回答 1

1

也许这就是你喜欢的?

public static void main(String[] args) throws MalformedURLException, IOException
{
    String text = "++ name1\n" +
            "description:asdfmkdfkmfkskfsaf \\n\n" +
            "++ name2\n" +
            "description:asdfmkdfkmfkskfsaf \\n\n" +
            "++ name3 description:asdfmkdfkmfkskfsaf\n" +
            "++ name4 :asdfmkdfkmfkskfsaf\n" +
            "++ name5 asdfmkdfkmfkskfsaf\n";
    System.out.println(text);


    System.out.println("\n\n\nResult:");
    Matcher matcher = Pattern.compile("\\+\\+ (.*?)\\s+(?:description)?:?([\\p{Alpha}]+)\\s*").matcher(text);
    //                                 ^           ^    `- the description "could" be there.              
    //                                 |            `- read the whitespaces and linebreaks 
    //                                 \ the two ++ and the whitespace
    //                                       

     while(matcher.find())
     {
         System.out.println(matcher.group(1) + " - " + matcher.group(2));
     }
}

它将打印:

Result:
name1 - asdfmkdfkmfkskfsaf
name2 - asdfmkdfkmfkskfsaf
name3 - asdfmkdfkmfkskfsaf
name4 - asdfmkdfkmfkskfsaf
name5 - asdfmkdfkmfkskfsaf
于 2013-08-23T20:14:19.960 回答