我有一个正则表达式,正在计算所有具有奇数X的字符串.
^[^X]*X(X{2}|[^X])*$
Run Code Online (Sandbox Code Playgroud)
几乎适用于所有情况:
X
XXX
XAA
AXXX
AAAX etc
Run Code Online (Sandbox Code Playgroud)
键入以下内容时失败:
XAXAXA
Run Code Online (Sandbox Code Playgroud)
我需要一个额外的子句,允许具有交替X的字符串是XAXA.X {2}*已经映射了连续的X模式.
以下正则表达式匹配由不均匀数量的字符串组成的字符串X:
^[^X]*(X[^X]*X[^X]*)*X[^X]*$
Run Code Online (Sandbox Code Playgroud)
快速分解:
^ # the start of the input
[^X]* # zero or more chars other than 'X'
( # start group 1
X[^X]* # an 'X' followed by zero or more chars other than 'X'
X[^X]* # an 'X' followed by zero or more chars other than 'X'
) # end group 1
* # repeat group 1 zero or more times
X # an 'X'
[^X]* # zero or more chars other than 'X'
$ # the end of the input
Run Code Online (Sandbox Code Playgroud)
因此,重复的组1导致匹配零,或者偶数X匹配,并且单个匹配,X使其不均匀.