Java Pattern / Matcher - 将匹配从一种方法返回到另一种方法

时间:2013-09-11 11:38:05

标签: java regex methods matcher

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

我有两个课程,一个用于浏览句子的arraylist。我只附上for-each循环,如下所示。 “matching”是另一个类的实例(包含模式/匹配器代码) 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)

提前非常感谢你!

5 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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<String>个句子并打印出所有以endings中的某个元素结尾的句子。如需使用,您可以尝试:

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

sentencesArrayList<String>个句子。

答案 2 :(得分:1)

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 ""
}

答案 3 :(得分:0)

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 "";
        }
    }       
}

答案 4 :(得分:0)

  • 不要在方法中构造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() {

            }
            };
    }

}