How to combine a repeating word separated by a metric

I want to create regexp that takes these values:

number:number [P]or [K]either both or nothing, and now he can repeat it again, separated by a separator [ + ], for example, valid values:

15:15
1:0
1:2 K
1:3 P
1:4 P K
3:4 + 3:2
34:14 P K + 3:1 P

What I created:

([0-9]+:[0-9]+( [K])?( [P])?( [+] )?)+

There is only one error in this example. It takes on the value:

15:15 K P +  

which should not be allowed.

How do I change it?

UPDATE:

I forgot to mention that it could be KP or P K. Or the values ​​are valid

1:4 K P
+4
source share
4 answers

Try this regex:

^([0-9]+:[0-9]+(?: P)?(?: K)?(?: \+ [0-9]+:[0-9]+(?: P)?(?: K)?)*)$

Online survey

UPDATE: . Based on your comment, you can use it to vice versa, but it will also match P PorK K

^([0-9]+:[0-9]+(?: [KP]){0,2}(?: \+ [0-9]+:[0-9]+(?: [KP]){0,2})*)$
0

K P:

^[0-9]+:[0-9]+( P| K| K P| P K)?( \+ [0-9]+:[0-9]+( P| K| K P| P K)?)*$
0

:

^(\d+:\d+(?:(?: P)?(?: K)?|(?: P)?(?: K)?)?)(?:\s\+\s(?1))?$

:

^               : start of string
(               : start capture group 1
    \d+:\d+     : digits followed by colon followed by digits
    (?:         : non capture group
    (?: P)?     : P in a non capture group optional
    (?: K)?     : K in a non capture group optional
    |           : OR
    (?: K)?     : K in a non capture group optional
    (?: P)?     : P in a non capture group optional
    )?          : optional
)               : end of group 1
(?:             : non capture group
    \s\+\s      : space plus space
    (?1)        : same regex than group 1
)?              : end of non capture group optional
$               : end of string
0

You can use this template:

^(?:[0-9]+:[0-9]+(?:( [KP])(?!\1)){0,2}(?: \+ |$))+$

more details:

^
(?:                    # this group describes one item with the optional +
    [0-9]+:[0-9]+
    (?:                # describes the KP part
        ( [KP])(?!\1)  # capture current KP and checks it not followed by itself
    ){0,2}             # repeat zero, one or two times
    (?: \+ |$)         # the item ends with + or the end of the string
)+$                    # repeat the item group

in Java style:

^(?:[0-9]+:[0-9]+(?:( [KP])(?!\\1)){0,2}(?: \\+ |$))+$
0
source

Source: https://habr.com/ru/post/1535561/


All Articles