【问题标题】:How to find multiple Pattern(s) (using Matcher) in Java如何在 Java 中查找多个模式(使用 Matcher)
【发布时间】:2012-03-15 15:47:37
【问题描述】:

假设我有一个String,比如one two three one one two one。 现在我使用PatternMatcherString 中查找任何特定的Pattern。 像这样:

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

但是,假设我想找到多种模式。对于我采取的示例String,我想同时找到onetwo。现在它是一个非常小的字符串,所以可能的解决方案是使用另一个 Pattern 并找到我的匹配项。但是,这只是一个小例子。有没有一种有效的方法来做到这一点,而不是在所有Patterns 集合中循环尝试?

【问题讨论】:

    标签: java regex


    【解决方案1】:

    使用正则表达式的强大功能:更改模式以匹配 onetwo

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

    【讨论】:

    • 我在问题中提到过,这只是一个小例子。如果我有很多,比如大约 100 多个要匹配的模式怎么办?
    • 使用循环动态创建字符串 one|two|three..
    • 这真的取决于你想要做什么。如果模式看起来仍然像您的示例中那样,则您根本不需要模式。您可以使用String#contains()。或者按照阿米特的建议去做。
    【解决方案2】:

    这不会解决我的问题,这样我们可以将 (one|two) 更改为特定的字符串。

    但我的要求是改变 模式一 -> 三和二 -> 四

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 2011-02-10
      相关资源
      最近更新 更多