有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

regex如何在Java中找到多个模式(使用Matcher)

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

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

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


共 (2) 个答案

  1. # 1 楼答案

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

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

    这并不能解决我的问题,这样我们就可以把(一|二)变成一个特定的字符串

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