educative.io

Educative

Characters Types and Meta-Characters - Mastering Regular Expressions in Java

String text = “The quick brown fox fox jumped over the fox fox and lazy dog.”;

// a simple character class
String searchText = "(fox)\\s\\1";

If I change the above text string how can I reference the second group of fox fox.

Hi @Balakrishna

Since we used an if statement in our code, so we are only checking for the first occurrence of the pattern and it returns that.

We can’t just reference the second group of “fox fox”. To get both the occurrences of the defined pattern, we’ll have to change the code in the following way.

import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Main {
public static void main(String[] args) {
String text = “The quick brown fox fox jumped over the fox fox and lazy dog”;
boolean flag = false;
// a simple character class
String searchText = “(fox)\s\1”;

// creating a pattern object
Pattern pattern = Pattern.compile(searchText);

// creating a matcher to find the pattern within the text
Matcher matcher = pattern.matcher(text);

while (matcher.find()){

  System.out.format("Found \"%s\", at positiong [%d-%d]\n", 
      matcher.group(), matcher.start(), matcher.end());
      flag = true;
} 
if (!flag)
{
  System.out.println("No match found");
}
}

}

Copy-paste this code in the code widget in the lesson and you’ll see both the occurrences being found.

Thanks