2012-03-15 55 views
0

假設我有String,比如one two three one one two one。 現在,我使用PatternMatcher來查找String中的任何特定Pattern。 想要這樣:如何在Java中找到多個模式(使用匹配器)

Pattern findMyPattern = Pattern.compile("one"); 
Matcher foundAMatch = findMyPattern.matcher(myString); 
while(foundAMatch.find()) 
      // do my stuff 

但是,假設我想找到多個模式。例如String我拿了,我想找到onetwo。現在它是一個相當小的字符串,所以可能的解決方案是使用另一個Pattern並找到我的匹配。但是,這只是一個小例子。有沒有一種有效的方式來做到這一點,而不是僅僅通過循環遍歷所有的Pattern

回答

6

使用正則表達式的力量:更改模式以匹配onetwo

Pattern findMyPattern = Pattern.compile("one|two"); 
Matcher foundAMatch = findMyPattern.matcher(myString); 
while(foundAMatch.find()) 
      // do my stuff 
+0

我已經在問題中提到它,這只是一個小例子。如果我有很多,比如說大約100多個模式可以匹配? – 2012-03-15 15:51:41

+3

只需創建字符串one | two | three ..動態使用循環 – 2012-03-15 15:52:30

+2

它確實取決於你想要做什麼。如果模式仍然看起來像您在示例中所做的那樣,則根本不需要模式。你可以使用'String#contains()'。或者做什麼艾米特建議。 – 2012-03-15 15:52:59

0

這不會解決我的問題,這樣我們可以更改(一|二)到一個相關的字符串。

但我requirementis改變 模式的一個 - >三& 2 - >四