假設我有String
,比如one two three one one two one
。 現在,我使用Pattern
和Matcher
來查找String
中的任何特定Pattern
。 想要這樣:如何在Java中找到多個模式(使用匹配器)
Pattern findMyPattern = Pattern.compile("one");
Matcher foundAMatch = findMyPattern.matcher(myString);
while(foundAMatch.find())
// do my stuff
但是,假設我想找到多個模式。例如String
我拿了,我想找到one
和two
。現在它是一個相當小的字符串,所以可能的解決方案是使用另一個Pattern
並找到我的匹配。但是,這只是一個小例子。有沒有一種有效的方式來做到這一點,而不是僅僅通過循環遍歷所有的Pattern
?
我已經在問題中提到它,這只是一個小例子。如果我有很多,比如說大約100多個模式可以匹配? – 2012-03-15 15:51:41
只需創建字符串one | two | three ..動態使用循環 – 2012-03-15 15:52:30
它確實取決於你想要做什麼。如果模式仍然看起來像您在示例中所做的那樣,則根本不需要模式。你可以使用'String#contains()'。或者做什麼艾米特建議。 – 2012-03-15 15:52:59