Regex 如何匹配delimeter分隔的重复词

Regex 如何匹配delimeter分隔的重复词,regex,Regex,我要创建接受以下值的regexp: number:number[p]或[K]或两者兼而有之或什么都不做,现在它可以再次重复它,并用分隔符[+]分隔,因此,例如,有效值为: 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 我创建的是: ([0-9]+:[0-9]+( [K])?( [P])?( [+] )?)+ 这个例子只有一个错误。它接受以下值: 15:15 K P + 这是不允许的 我应该如何改变它 更新: 我忘了提

我要创建接受以下值的regexp:

number:number[p]
[K]
或两者兼而有之或什么都不做,现在它可以再次重复它,并用分隔符
[+]
分隔,因此,例如,有效值为:

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
我创建的是:

([0-9]+:[0-9]+( [K])?( [P])?( [+] )?)+
这个例子只有一个错误。它接受以下值:

15:15 K P +  
这是不允许的

我应该如何改变它

更新:

我忘了提到它可以是KP或PK,或者值是有效的

1:4 K P
试试这个正则表达式:

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

更新::根据您的评论,您可以使用此选项,反之亦然,但它也将匹配
PP
K

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

此正则表达式支持K和p的任何订单:

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

^(\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-9]+:[0-9]+(?:( [KP])(?!\1)){0,2}(?: \+ |$))+$
图案详情:

^
(?:                    # 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
Java风格:

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

没有
K
P
的强制顺序,即它可以是
kp
pk
?我更新我的问题这两个值都是有效的正则表达式引擎(或编程语言)你在使用吗?@sp00m我在使用Java你需要分别提取不同的项目吗?嗯,很好,我忘了添加一件事,它应该接受P和K,反之亦然,所以1:4 K P。你能更新你的答案吗?但是当我在这里尝试你的示例时:它不像@Sabuj Hassan示例那样工作,当我在34:14 P K+3:1 P上尝试它时(你给出的最长的示例行)我得到:匹配11.[5-9]`pk`2.[9-17]`+3:1p`3.[15-17]`P`你能提供一些在线regexp测试工具吗?我试了一个,似乎不起作用correctly@hudi:这个正则表达式已经过测试,我把它写成了一个原始模式,你必须用双反斜杠替换所有反斜杠。