0

In Java, is there a way to use indexOf() or lastIndexOf() with a regex expression inside, like used in replaceAll(), to find out the indexes (of the first and last indexes of a character) that match the regex expression in the String ?

Pepe
  • 301
  • 4
  • 13
  • 1
    Can you provide examples of you are trying to accomplish? Sample input, Expected output? Also, what you've tried and actual output if you have it – dvo Sep 20 '19 at 14:42
  • 4
    No, these methods don't accept regular expressions. But you can use the regex `Matcher` to repeatedly `find()` matches, then get detailed index values using the `start`, `end` and `group` methods. – f1sh Sep 20 '19 at 14:42

1 Answers1

0

Forexample here is a regex pattern which finds 3 'w' next to each other. m.find() tries to find a match and returns true if it succeeds. By using m.start() after each m.find() you get the first index of the found match and by m.end() you get last index of found match

Pattern p = Pattern.compile("w{3}");
Matcher m = p.matcher("www lskjdflkj www sdflkjslkjlk fsdlkfjww lksjfkjwww sldklk wwwlskjdflkjwwwlkjlj lkj");
    while(m.find())
    {
        System.out.println("start index:"+m.start()+", end index:"+m.end());
    }

output:

start index:0, end index:3
start index:14, end index:17
start index:48, end index:51
start index:59, end index:62
start index:71, end index:74

You can store the found indexes in a HashMap or something else to use later(if you need to)

Soheil Rahsaz
  • 719
  • 7
  • 22