通过正则表达式在 Notepad++ 中替换时如何使用条件
How to use conditionals when replacing in Notepad++ via regex
考虑以下正则表达式:
([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 ''
假设,我想在 Notepad++ 中查找并替换此字符串,如果 /2
或 /4
为空(如上述第一种情况),我会在前面添加 c
。
因此,文本 a/b
变为 ca/cb
。
文本 aa/b
变为 aa/cb
我使用以下正则表达式进行替换:
(?(2)|0)/(?(4)|0)
但 Notepad++ 在这种情况下按字面意思处理 ?
,而不是作为条件标识符。知道我做错了什么吗?
条件替换中的语法是
(?{GROUP_MATCHED?}REPLACEMENT_IF_YES:REPLACEMENT_IF_NO)
在处理大于 9 的组和命名捕获组时,{
和 }
是避免歧义的必要条件。
由于 Notepad++ 使用 Boost-Extended Format String Syntax
,请参阅此 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, then true-expression
is evaluated and sent to output, otherwise false-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 with foo
if the sub-expression </code> was matched, and with <code>bar
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}:c)/(?{4}:c)
。
第二个问题是您将 ?
量词放在捕获组内,使组内的模式可选,但不是整个组。这使得该组始终“参与匹配”,并且条件始终为“真”(始终匹配)。 ?
应该量化组.
考虑以下正则表达式:
([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 ''
假设,我想在 Notepad++ 中查找并替换此字符串,如果 /2
或 /4
为空(如上述第一种情况),我会在前面添加 c
。
因此,文本 a/b
变为 ca/cb
。
文本 aa/b
变为 aa/cb
我使用以下正则表达式进行替换:
(?(2)|0)/(?(4)|0)
但 Notepad++ 在这种情况下按字面意思处理 ?
,而不是作为条件标识符。知道我做错了什么吗?
条件替换中的语法是
(?{GROUP_MATCHED?}REPLACEMENT_IF_YES:REPLACEMENT_IF_NO)
在处理大于 9 的组和命名捕获组时,{
和 }
是避免歧义的必要条件。
由于 Notepad++ 使用 Boost-Extended Format String Syntax
,请参阅此 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</code> was matched, and with <code>bar
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}:c)/(?{4}:c)
。
第二个问题是您将 ?
量词放在捕获组内,使组内的模式可选,但不是整个组。这使得该组始终“参与匹配”,并且条件始终为“真”(始终匹配)。 ?
应该量化组.