0

我有一个像

"SimpleKey1: word1. SimpleKey2Word1 SimpleKey2Word2: word word word, word word. word word. CompoundKey3 / CompoundKey3: word word word, word. Key3: word. CompoundKey4Word1 CompoundKey4Word2 / CompoundKey4Word3 CompoundKey4Word4: word words, words word-word (word 18 word 100 ). CompoundKey5 / CompoundKey5: word word."

我需要解析该字符串以获得键/值映射,例如:

SimpleKey1: word1. 
SimpleKey2Word1 SimpleKey2Word2: word word word, word word. word word. 
CompoundKey3 / CompoundKey3: word word word, word. 
CompoundKey4Word1 CompoundKey4Word2 / CompoundKey4Word3 CompoundKey4Word4: word words,    words word-word (word 18 word 100 ).  
CompoundKey5 / CompoundKey5: word word.

请注意,键可以包含斜杠字符 (/),值可以包含特殊字符。

我不知道应该使用什么正则表达式。

谢谢。

4

2 回答 2

4
String data = "SimpleKey1: word1. SimpleKey2Word1 SimpleKey2Word2: word "
            + "word word, word word. word word. CompoundKey3 / CompoundKey3: "
            + "word word word, word. Key3: word. CompoundKey4Word1 "
            + "CompoundKey4Word2 / CompoundKey4Word3 CompoundKey4Word4: word "
            + "words, words word-word (word 18 word 100 ). CompoundKey5 / "
            + "CompoundKey5: word word.";
Pattern p=Pattern.compile("([\\w\\s/]+):(.*?)(?=$|([\\w\\s/]+):)");
Matcher m=p.matcher(data);
while(m.find())
    System.out.println(m.group().trim());

输出:

SimpleKey1: word1.
SimpleKey2Word1 SimpleKey2Word2: word word word, word word. word word.
CompoundKey3 / CompoundKey3: word word word, word.
Key3: word.
CompoundKey4Word1 CompoundKey4Word2 / CompoundKey4Word3 CompoundKey4Word4: word words, words word-word (word 18 word 100 ).
CompoundKey5 / CompoundKey5: word word.

如果你想获得密钥使用m.group(1)。为了价值,您可以m.group(2)使用

while(m.find()){
    System.out.println("key=>"+m.group(1));
    System.out.println("value=>"+m.group(2));
}
于 2012-07-13T21:54:33.020 回答
0

试试这个正则表达式(.+?)(?=\.\s*(([A-Z])|($)))

于 2012-07-13T21:50:34.320 回答