正则表达式匹配特殊字符

时间:2013-08-23 20:05:48

标签: regex

我有一个类似于此的字符串:

++ name1
description:asdfmkdfkmfkskfsaf \n

++ name2
description:asdfmkdfkmfkskfsaf \n

++ name3 description:asdfmkdfkmfkskfsaf

我想将其提取为以下组:

group1:
name1
description:asdfmkdfkmfkskfsaf

group2:
name2
description:asdfmkdfkmfkskfsaf

group3:
name3
description:asdfmkdfkmfkskfsaf

如何使用正则表达式执行此操作?

1 个答案:

答案 0 :(得分: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