7

Regex stops at first occurrence in java

 2 years ago
source link: https://www.codesd.com/item/regex-stops-at-first-occurrence-in-java.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Regex stops at first occurrence in java

advertisements

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)


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);
    }
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK