IllegalStateException with Pattern/Matcher

后端 未结 1 843
轮回少年
轮回少年 2021-01-26 14:58

I\'m using Matcher to capture groups using a regular expression in Java and it keeps throwing an IllegalStateException even though I know that the expression matche

相关标签:
1条回答
  • 2021-01-26 15:08

    Matcher is helper class which handles iterating over data to search for substrings matching regex. It is possible that entire string will contain many sub-strings which can be matched, so by calling group() you can't specify which actual match you are interested in. To solve this problem Matcher lets you iterate over all matching sub-strings and then use parts you are interested in.

    So before you can use group you need to let Matcher iterate over your string to find() match for your regex. To check if regex matches entire String we can use matches() method instead of find().

    Generally to find all matching substrings we are using

    Pattern p = Pattern.compiler("yourPattern");
    Matcher m = p.matcher("yourData");
    while(m.find()){
        String match = m.group();
        //here we can do something with match... 
    }
    

    Since you are assuming that text you want to find exists only once in your string (at its end) you don't need to use loop, but simple if (or conditional operator) should solve your problem.

    Matcher m = Pattern.compile("(\\.\\w+)$").matcher("google.ca");
    String safeName = m.find() ? m.group() : null;
    
    0 讨论(0)
提交回复
热议问题