Java Regex Group 0

Can someone please help me explain the following code? Thank you I am a little confused about grouping regular expressions.

public static String evaluate(String s) { if (s == null) return ""; Matcher m = Pattern.compile("[0-9]*").matcher(s); if (m.find()) { MatchResult mr = m.toMatchResult(); return mr.group(0); } return ""; } 
+4
source share
2 answers

From the documentation :

Group zero indicates the entire template , so the expression m.group(0) equivalent to m.group() .

In other words, mr.group(0) is a complete match.

+8
source

We hope this makes group 0 clearer:

Example:

  String str = "start123456end"; // Your input String // Group#1 Group#2 // | | Pattern p = Pattern.compile("start([0-9]*)(end)"); // |<--- Group#0 --->| Matcher m = p.matcher(str); // Create a matcher for regex and input while( m.find() ) // As long as your regex matches something { System.out.println("group#0:\t" + m.group()); // Or: m.group(0) System.out.println("group#1:\t" + m.group(1)); System.out.println("group#2:\t" + m.group(2)); } 

Output:

 group#0: start123456end group#1: 123456 group#2: end 

You can “save” some parts of your regular expression into groups. in my example you have 3 of them (groups are between ( and ) ):

  • Group 1: numbers between start and end words.
  • Group 2: final word only
  • Group 0: that is, everything that matches your template group 0 is reserved and will always return a whole match, while all the others are optional and defined by you.

According to your code:

Example:

 Matcher m = Pattern.compile("[0-9]*").matcher("123456end"); // Matches all numbers if( m.find() ) { System.out.println(m.group(0)); // m.group() possible too } 

Only one group: 0 !

Output: 123456 (= group 0)

now allows you to put several more groups in the template:

Code:

  // Group#1 Group#2 // | | Matcher m = Pattern.compile("([0-9])[0-9]([0-9])*").matcher(str); // Matches all numbers // |<---- Group#0 ---->| if( m.find() ) { System.out.println("group#0:\t" + m.group(0)); // m.group() possible too System.out.println("group#1:\t" + m.group(1)); // 1st digit System.out.println("group#2:\t" + m.group(2)); // 3rd digit } 

Now there are two groups.

Output:

 group#0: 123456 group#1: 1 group#2: 6 

I recommend you this documentation: Lesson: regular expressions . Start with the first chapter and try your examples.

Additionally:

+7
source

All Articles