Chènevis
Chènevis

Reputation: 513

Regex stops at first occurrence in java

I think there is a problem with my regex because when I looked for resolve my problem, I found only question about wanted to stop at the first occurrence. Although, I want my regex to go after the first occurrence.

Here is my code:

String test = "\\d";
String word = "a1ap1k7";

Pattern p = Pattern.compile(test);
Matcher b = p.matcher(word);

if (b.find()) {
    int start = b.start();
    String text = b.group();
    int stop = b.end();
    System.out.println(start + text + stop);
}

It gives me just: 1(for the start)1(for the text)2(for the end)

Upvotes: 1

Views: 888

Answers (2)

Pshemo
Pshemo

Reputation: 124215

If you change your print statement to

System.out.println(start +":"+ text +":"+ stop);

you will see that result is 1:1:2 which means that you found only match between characters indexed from 1 till 2.

If you want to find all matches like

1:1:2
4:1:5
6:7:7

instead of if (b.find()) which can execute only once, use loop while (b.find()) since each find can move you to one (next) match.

while (b.find()) {// <-- change 'if' to 'while'
    int start = b.start();
    String text = b.group();
    int stop = b.end();
    System.out.println(start +":"+ text +":"+ stop);
}

Upvotes: 3

d0nut
d0nut

Reputation: 2834

You made just a simple error in writing this. You have to keep calling find

public static void main(String[] args){

    String test = "\\d";
    String word = "a1ap1k7";

    Pattern p = Pattern.compile(test);
    Matcher b = p.matcher(word);

    while (b.find())
    {
        int start = b.start();
        String text = b.group();
        int stop = b.end();
        System.out.println(start + text + stop);
    }
}

Upvotes: 4

Related Questions