简体   繁体   中英

Count of a particular string in given line using regex java

I have a line for ex HelloxyzxyzxyzHello

I have a below regex to match this line

private static final Pattern matchPat = Pattern.compile("Hello(xyz)*Hello");
String line = "HelloxyzxyzxyzHello";
Matcher x8 = matchPat.matcher(line);

Now I would like to get the count of xyz In my line it is 3

Is there a ready API available from regex other than finding a each matching pattern and use counter.

Try this:

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "HelloxyzxyzxyzHello";
        Pattern pattern = Pattern.compile("xyz");
        Matcher  matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 3
    }
}

EDIT: Capturing Groups

String line = "This order was placed for QT3000! OK?";
Pattern pattern = Pattern.compile("(.*?)(\\d+)(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    System.out.println("group 1: " + matcher.group(1));
    System.out.println("group 2: " + matcher.group(2));
    System.out.println("group 3: " + matcher.group(3));
}

You could try the below regex to get all the xyz count which was present inside two Hello substrings.

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "HelloxyzxyzxyzHello";
        Pattern pattern = Pattern.compile("(?:Hello|(?<!^)\\G)(?:(?!Hello).)*?(xyz)(?=.*?Hello)");
        Matcher  matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find()) {
            if (matcher.group(1)) {
            count++;
             }
         }
        System.out.println(count);    // prints 3
    }
}

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM