1

I need to make a regex for this

example

math(5),English(6),P.E(5)

1 Answers1

0

I'm guessing that maybe,

(?<=,|^)([^(,]*)\((\d*)\)(?=,|$)

might be close to what you have in mind.

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class re{

    public static void main(String[] args){

        final String regex = "(?<=,|^)([^(,]*)\\((\\d*)\\)(?=,|$)";
        final String string = "math(5),English(6),P.E(5)";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }

    }
}

Output

Full match: math(5)
Group 1: math
Group 2: 5
Full match: English(6)
Group 1: English
Group 2: 6
Full match: P.E(5)
Group 1: P.E
Group 2: 5

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Emma
  • 1
  • 9
  • 28
  • 53