2012-03-15 109 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 - >四