假设我有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