Simple java regex throws deadstateexception

I'm trying to do a quick sanity check ... and its failure. Here is my code -

import java.util.regex.*; public class Tester { public static void main(String[] args) { String s = "a"; Pattern p = Pattern.compile("^(a)$"); Matcher m = p.matcher(s); System.out.println("group 1: " +m.group(1)); } } 

And I would expect to see group 1: a . But instead, I get an IllegalStateException: no match found , and I have no idea why.

Edit: I am also trying to print groupCount() , and it says there is 1.

+4
source share
3 answers

You must use m.find() or m.matches() to use m.group .

  • find can be used to find each substring that matches your pattern (used mainly in situations where there is more than one match)
  • matches checks to see if the whole line matches your pattern, so you don’t even need to add ^ and $ to your pattern.

We can also use m.lookingAt() , but now let's skip its description (you can read it in the documentation).

+11
source

Use the Matcher # matches or the Matcher # to find before to call Matcher.group(int)

 if (m.find()) { System.out.println("group 1: " +m.group(1)); } 

In this case, Matcher#find more suitable, since Matcher#matches full String (which makes the anchor characters redundant in the corresponding expression)

+4
source

Check out the javadocs for Matcher . You will see that "attempting to request any part of it before a successful match will throw an IllegalState exception."

Wrap your group(1) call with if (matcher.find()) {} to solve this problem.

+2
source

Source: https://habr.com/ru/post/1497280/


All Articles