末匹配我有一個字符串,它是採用以下格式:模式的字符和行
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:).*?(?=,)");
的$
意味着結束行。
因此這應該工作:
Pattern pattern = Pattern.compile("(?<=Hello:).*?(?=,|$)");
所以你看,提前爲逗號或最終的線。
Test。
試試這個:
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);
感謝評論Dukeling,但不工作。事實上它甚至不匹配即使A; B; C。 是的,我正在尋找,或結束行。 – Brinal
[它似乎適用於我](https://ideone.com/OAo4lC)。 – Dukeling
Dukeling,是的,它工作正常。 非常感謝。 – Brinal