Regular expression works on online tester but doesn't work in java

I have the following regex ( link )

[\d\.]+[ ](.*?)[ ]{2,}(.+) 

However, the equivalent Java code does not match:

 String REGEX = "[\\d\\.]+[ ](.*?)[ ]{2,}(.+)"; Pattern pattern = Pattern.compile(REGEX); String line = "1. QUEEN WE ARE THE CHAMPIONS" Matcher matcher= pattern.matcher(line); String artist = matcher.group(0); String song = matcher.group(1); 

I can’t understand what’s going wrong, any ideas?

+6
source share
2 answers

You need to call find to go to the first match. Add matcher.find(); before calling group() .

Once you do this, your code works as expected.

+5
source

You need to call matcher.matches () in front of the group.

 if(matcher.matches()){ String artist = matcher.group(0); System.out.println(artist); String song = matcher.group(1); System.out.println(song); } 
+1
source

All Articles