0

I need to regex a string.

<NAME> [NUM1:]<NUM2>

I want to get mandatory NAME and NUM2. I do not need the optional NUM1. If NUM1 is present is is separated by a : to NUM2.

E.g.

tim 20         => NAME: tim,   NUM2: 20
tommy 123      => NAME: tommy, NUM2: 123
eve 9:234      => NAME: eve,   NUM2: 234

Thats my pattern and matching. It is working well.

Pattern pat = Pattern.compile ("^(.+)\\ ([0-9]\\:)?(.+?)$");
Matcher mat = patp.matcher (myline);
if (matpack.matches () == true)
{
  System.out.println ("NAME: " + mat.group (1) + ", NUM2: " + mat.group (3));
}

As you can see I have ( ) around the optional NUM1 to say the number AND the : are optional (?). Therefore I need to use group 1 (NAME) and group 3 (NUM2) to get the matching values.

How can I change my regex-term to group the number and the : of NUM1 together for the ? but not have it as a group?

I want to have group 1 for NAME and group 2 for NUM2.

chris01
  • 10,921
  • 9
  • 54
  • 93
  • 1
    `(?:[0-9]\\:)` https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-in-regular-expressions – Nick Mar 02 '23 at 06:36

0 Answers0