0

我有一个格式如下的字符串:

I am extracting this Hello:A;B;C, also Hello:D;E;F

如何提取字符串A;B;CD;E;F

我写了下面的代码片段来提取但无法提取最后一个匹配的字符D;E;F

Pattern pattern = Pattern.compile("(?<=Hello:).*?(?=,)");
4

3 回答 3

0

表示行$尾。

因此这应该有效:

Pattern pattern = Pattern.compile("(?<=Hello:).*?(?=,|$)");

因此,您可以提前查找逗号或换行符。

测试

于 2013-06-27T13:10:12.880 回答
0

尝试这个:

String test = "I am extracting this Hello:Word;AnotherWord;YetAnotherWord, also Hello:D;E;F";
// any word optionally followed by ";" three times, the whole thing followed by either two non-word characters or EOL
Pattern pattern = Pattern.compile("(\\w+;?){3}(?=\\W{2,}|$)");
Matcher matcher = pattern.matcher(test);
while (matcher.find()) {
    System.out.println(matcher.group());
}

输出:

Word;AnotherWord;YetAnotherWord
D;E;F
于 2013-06-27T13:11:47.307 回答
-1

假设您的意思是省略字符串中的某些模式:

    String s = "I am extracting this Hello:A;B;C, also Hello:D;E;F" ;
    ArrayList<String> tokens = new ArrayList<String>();

    tokens.add( "A;B;C" );
    tokens.add( "D;E;F" );

    for( String tok : tokens )
    {
        if( s.contains( tok ) )
        {
            s = s.replace( tok, "");
        }
    }
    System.out.println( s );
于 2013-06-27T13:31:24.057 回答