([A-ZA-Z])([A-ZA-Z])/([A-ZA-Z])([A-ZA-Z])
如果文字是:a / b
捕获组将是:
/1 'a' /2 '' /3 'b' /4 ''
如果文字是:aa / b
捕获组将是:
/1 'a' /2 'a' /3 'b' /4 ''
假设,我想在记事本中找到并替换此字符串,以便如果/ 2或/ 4为空(如上面的第一种情况),我会预先添加c.
因此,文本a / b变为ca / cb.
文本aa / b变为aa / cb
我使用以下正则表达式替换:
(?(2)\1\2|0\1)/(?(4)\3\4|0\3)
但记事本正在治疗?在这种情况下,字面上并不是条件标识符.知道我做错了什么吗?
(?{GROUP_MATCHED?}REPLACEMENT_IF_YES:REPLACEMENT_IF_NO}
当处理高于9的组和命名捕获组时,{和}是避免歧义的必要条件.
由于记事本使用Boost扩展格式字符串语法,请参阅此Boost documentation:
The character
?
begins a conditional expression,the general form is:
?Ntrue-expression:false-expression
where
N
is decimal digit.If sub-expression
N
was matched,thentrue-expression
is evaluated and sent to output,otherwisefalse-expression
is evaluated and sent to output.You will normally need to surround a conditional-expression with parenthesis in order to prevent ambiguities.
For example,the format string
(?1foo:bar)
will replace each match found withfoo
if the sub-expression$1
was matched,and withbar
otherwise.For sub-expressions with an index greater than 9,or for access to named sub-expressions use:
?{INDEX}true-expression:false-expression
or
?{NAME}true-expression:false-expression
那么,使用([a-zA-Z])([a-zA-Z])?/([a-zA-Z])([a-zA-Z])?并替换为(?{2} $1 $2:c $1)/(?{4} $3 $4:c $3).
第二个问题是你放了?捕获组内的量词,使组内的模式可选,但不是整个组.这使得该组始终“参与比赛”,并且条件将始终为“真实”(始终匹配). ?应量化该群体.