glearn
glearn

Reputation: 61

Index of each matcher group of a pattern in Java

I am matching certain contents of a file against a regex and getting groups out of it. How can I get the start and the end positions of each matched group? Need the positions to replace those parts Any suggestions please ?

Upvotes: 2

Views: 6496

Answers (3)

D. Karchnak
D. Karchnak

Reputation: 101

You're looking for methods m.start(int groupId) and m.end(int groupId)

Java Docs: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#start(int)

In this case I would consider using named capture groups (?<GROUP-NAME>YOUR_REGEX) and methods m.start("GROUP-NAME") and m.end("GROUP-NAME"). This way when you change your input text or add/remove some groups, your group names are staying the same. :)

Upvotes: 6

freedev
freedev

Reputation: 30237

The following code prints the text matching the regular expression and the start and end position within the text:

String text = "a long text regex to match";
Matcher m = Pattern.compile("regex").matcher(text);

while (m.find()){
    String found = m.group();
    System.out.println(found + " " + m.start() + " " +  m.end());
}

Upvotes: 4

Loic P.
Loic P.

Reputation: 711

You can directly replace your desired content with replaceAll function:

This method replaces each substring of this string that matches the given regular expression with the given replacement.

Then, you can use it like:

replaceAll("[0-9]", "X");

Hope it helps you!

Upvotes: 0

Related Questions