字符和行尾的模式匹配

时间:2013-06-27 13:02:34

标签: java regex pattern-matching

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

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:).*?(?=,)");

3 个答案:

答案 0 :(得分:0)

$表示行尾。

因此这应该有效:

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

所以你要先看一下逗号或行尾。

Test

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

答案 2 :(得分:-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 );