我有一个格式如下的字符串:
I am extracting this Hello:A;B;C, also Hello:D;E;F
如何提取字符串A;B;C
和D;E;F
?
我写了下面的代码片段来提取但无法提取最后一个匹配的字符D;E;F
Pattern pattern = Pattern.compile("(?<=Hello:).*?(?=,)");
我有一个格式如下的字符串:
I am extracting this Hello:A;B;C, also Hello:D;E;F
如何提取字符串A;B;C
和D;E;F
?
我写了下面的代码片段来提取但无法提取最后一个匹配的字符D;E;F
Pattern pattern = Pattern.compile("(?<=Hello:).*?(?=,)");
尝试这个:
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
假设您的意思是省略字符串中的某些模式:
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 );