从正则表达式中删除重复项
Remove duplication from regex
我正在使用以下正则表达式,但如您所见,表达式中有很多递归。
有没有更好的方法来解决这个问题?
我需要的是一种 "jump" 运算符。
((letzter|voriger|letztes|voriges) (lied|title|song))( (höhren|abspielen))?|((lied|title|song)( (wiederholen|erneut (höhren|abspielen))))
PCRE 实现 subroutine calls,以完全 实现您所需要的。
(?P<groupname>subpattern)
定义了一个组。
\g<groupname>
呼叫群
正则表达式:
/
(?:(?P<relative>letzte[rs]|vorige[rs])[ ])? # optional non-capturing group
(?P<what>lied|title|song)
(?(relative) # IF group <relative> was matched
(?:[ ](?P<action>höhren|abspielen))? # another optional non-capturing group
|
[ ](wiederholen|erneut[ ]\g<action>) # subroutine call to group <action>
)
/ix
PCRE 允许一些定义组的方法,它们都具有相同的含义:
(regex)
组
(?P<name>regex>
组名为 name.
(?'name'regex)
组名为 name.
(?<name>regex)
组名为 name.
以及调用子程序的不同方式:
(?3)
Recurse/call 第 3 组。
\g<3>
Recurse/call 第 3 组。
\g'3'
Recurse/call 第 3 组。
(?-1)
Recurse/call 上一组。
\g<-1>
Recurse/call 上一组。
\g'-1'
Recurse/call 上一组。
\g<-1>
Recurse/call 上一组。
(?&name)
Recurse/call 组名为 name.
(?P>name)
Recurse/call 组名为 name.
\g<name>
Recurse/call 组名为 name.
\g'name'
Recurse/call 组名为 name.
我正在使用以下正则表达式,但如您所见,表达式中有很多递归。
有没有更好的方法来解决这个问题?
我需要的是一种 "jump" 运算符。
((letzter|voriger|letztes|voriges) (lied|title|song))( (höhren|abspielen))?|((lied|title|song)( (wiederholen|erneut (höhren|abspielen))))
PCRE 实现 subroutine calls,以完全 实现您所需要的。
(?P<groupname>subpattern)
定义了一个组。\g<groupname>
呼叫群
正则表达式:
/
(?:(?P<relative>letzte[rs]|vorige[rs])[ ])? # optional non-capturing group
(?P<what>lied|title|song)
(?(relative) # IF group <relative> was matched
(?:[ ](?P<action>höhren|abspielen))? # another optional non-capturing group
|
[ ](wiederholen|erneut[ ]\g<action>) # subroutine call to group <action>
)
/ix
PCRE 允许一些定义组的方法,它们都具有相同的含义:
(regex)
组(?P<name>regex>
组名为 name.(?'name'regex)
组名为 name.(?<name>regex)
组名为 name.
以及调用子程序的不同方式:
(?3)
Recurse/call 第 3 组。\g<3>
Recurse/call 第 3 组。\g'3'
Recurse/call 第 3 组。(?-1)
Recurse/call 上一组。\g<-1>
Recurse/call 上一组。\g'-1'
Recurse/call 上一组。\g<-1>
Recurse/call 上一组。(?&name)
Recurse/call 组名为 name.(?P>name)
Recurse/call 组名为 name.\g<name>
Recurse/call 组名为 name.\g'name'
Recurse/call 组名为 name.