【问题标题】:Java Pattern/Matcher - Return the matches from one method to anotherJava Pattern/Matcher - 将匹配项从一种方法返回到另一种方法
【发布时间】:2013-09-11 11:38:05
【问题描述】:

我是一个绝对的 Java 初学者。我在论坛上搜索过,但找不到这个问题的答案。

我有两个类,一个浏览句子数组列表。我只附加了 for-each 循环,如下所示。 “匹配”是另一个类的实例(包含模式/匹配器代码) matchEndings 是方法,附在下面。

for (String sentence: sentences) {
    String match = matching.matchEndings(sentence);
    if (match.length() > 0) {
        System.out.println(match);
    }
}

这就是方法。

public String matchEndings(String s){
Pattern p = Pattern.compile(".*?(aa|ee)");
Matcher m = p.matcher(s);

return m.group();

}

我的问题是,如何将包含 aa / ee 结尾的匹配句子返回到第一堂课,并将其打印在那里?代码已编译,但是当我运行时,我得到了


Exception in thread "main" java.lang.IllegalStateException: No match found
        at java.util.regex.Matcher.group(Unknown Source)
        at java.util.regex.Matcher.group(Unknown Source)

非常感谢您!

【问题讨论】:

  • 所以你想打印出所有以aa或ee结尾的行?
  • 是的,就是这样!

标签: java regex methods matcher


【解决方案1】:

Matcher.group() 仅在已有匹配项时返回。你需要做这样的事情:-

if (m.matches()) {
    return m.group();
} else {
    return "";
}

【讨论】:

  • 谢谢大家!我现在唯一的问题是它只在“句子”中找到第一次出现。如果字符串是“Hee Aaa Oaa”后跟换行符,则只返回“Hee”。我知道如果我想打印结果,while (m.find()) 会起作用,但不是现在,当我打算返回它时。数组列表“句子”由来自文本文件的扫描仪填充。扫描仪 in = new Scanner(new File(args[0])); while (in.hasNextLine()) { sentence.add(in.nextLine());不知道如何进行。也许你能帮帮我!在此先感谢各位
  • 您的目的是返回字符串中所有以 ee 或 aa 结尾的单词吗?
  • 是的!这就是我打算做的。
【解决方案2】:

当您只需要一个简单的endsWith(String) 时,使用 RegEx 似乎有点过头了:

public void print(final List<String> sentences, final String... endings){
    for(final String sentence : sentences){
        for(final String ending : endings){
            if(sentence.endsWith(ending)){
                System.out.println(sentence);
                break;
            }
        }
    }
}

上面的方法将遍历一个List&lt;String&gt;的句子,并打印出所有以endings中的元素之一结尾的句子。对于用法,您可以尝试:

print(sentences, "aa", "ee");

其中sentences 是您的ArrayList&lt;String&gt; 句子。

【讨论】:

    【解决方案3】:

    matchesfind 方法必须在 group 方法之前。由于matches 试图将整个区域与模式匹配,所以这里更合适

    public String matchEndings(String s){
       Pattern p = Pattern.compile("(aa|ee)$");
       Matcher m = p.matcher(s);
    
    if (m.matches) {
       return m.group();
    } else {
       return ""
    }
    

    【讨论】:

      【解决方案4】:
      import java.util.ArrayList;
      import java.util.regex.Matcher;
      import java.util.regex.Pattern;
      public class PotenssienSumma {
          public static void main(String[] args) {            
              ArrayList<String> sentences = new ArrayList<>(10);
              sentences.add("aa");
              sentences.add("1324");
              for (String sentence: sentences) {
                  String match = Matching.matchEndings(sentence);
                  if (match.length() > 0) {
                       System.out.println(match);
                  }
              }
          }
      }   
      class Matching{         
          public  static String matchEndings(String s){
              Pattern p = Pattern.compile(".*?(aa|ee)");
              Matcher m = p.matcher(s);
              if (m.matches()) {
                  return m.group();
              } else {
                  return "";
              }
          }       
      }
      

      【讨论】:

        【解决方案5】:
        • 不要在方法中构造 Pattern。那是昂贵的。将模式对象放入静态最终变量中。

        • 模式的正确用法如下:

          while(matcher.find()) {
              sysout(matcher.group());
          }
          

        这将打印所有匹配项,如果您只想要一个匹配项,请将 while 替换为 if

        • 我不知道这是否是故意的,但您的正则表达式与字符串末尾的 ee|aa 不匹配。它匹配字符串中任何位置的eeaa 以及它前面的任何字符。例如对于字符串Fox preens in front of a vixen,您的正则表达式返回字符串Fox pree。不知道这是不是故意的。

        这是一个将字符串列表或字符串集合作为参数的类,然后懒惰地查找所有以aaee 结尾的单词。它有一个main 方法,你可以运行它来测试。

            public class Endings implements Iterable<String> {
                private final Iterable<String> strings;
                private static final Pattern pat = Pattern.compile("(?<=^|\\s)\\S*(aa|ee)(?=\\s|$)");
        
                public static void main(String[] args) {
                    Endings endings = new Endings(Arrays.asList("This testaabb testee testaa", "Test2aa Test3ee ", "no match"));
                    for(String word : endings) {
                        System.out.println(word);
                    }
                }
        
                public Endings(Iterable<String> strings) {
                    this.strings = strings;
                }
        
                public Iterator<String> iterator() {
                    return new Iterator<String>() {
                    private Iterator<String> iter = strings.iterator();
                    private Matcher m;
                    private String result;
                    public boolean hasNext() {
                        if (result == null) {
                            if (m == null) {
                                if (iter.hasNext()) {
                                    m = pat.matcher(iter.next());
                                } else {
                                    return false;
                                }
                            }
                            if (m.find()) {
                                result = m.group();
                                return true;
                            } else {
                                m = null;
                                return hasNext();
                            }
                        } else {
                            return true;
                        }
                    }
        
                    public String next() {
                        if (result != null) {
                            String ret = result;
                            result = null;
                            return ret;
                        } else {
                            throw new NoSuchElementException();
                        }
                    }
        
                    public void remove() {
        
                    }
                    };
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 2017-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-09
          • 2022-11-29
          • 2018-12-24
          相关资源
          最近更新 更多