通过正则表达式在 Notepad++ 中替换时如何使用条件 [英] How to use conditionals when replacing in Notepad++ via regex

查看:28
本文介绍了通过正则表达式在 Notepad++ 中替换时如何使用条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下正则表达式:

([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 '一个'/3 'b'/4 ''

假设,我想在 Notepad++ 中找到并替换这个字符串,如果 /2/4 为空(如上面的第一种情况),我在前面加上c.

所以,文本a/b 变成了ca/cb.而文本 aa/b 变成了 aa/cb

我使用以下正则表达式进行替换:

(?(2)12|01)/(?(4)34|03)

但 Notepad++ 在这种情况下按字面意思处理 ?,而不是作为条件标识符.知道我做错了什么吗?

解决方案

条件替换中的语法是

(?{GROUP_MATCHED?}REPLACEMENT_IF_YES:REPLACEMENT_IF_NO)

{} 是必要的,以避免在处理大于 9 的组和命名捕获组时产生歧义.

由于 Notepad++ 使用 Boost 扩展格式字符串语法,请参阅此

Consider the following regex:

([a-zA-Z])([a-zA-Z]?)/([a-zA-Z])([a-zA-Z]?)

If the text is: a/b the capturing groups will be:

/1  'a'
/2  ''
/3  'b'
/4  ''

And if the text is: aa/b the capturing groups will be:

/1  'a'
/2  'a'
/3  'b'
/4  ''

Suppose, I want to find and replace this string in Notepad++ such that if /2 or /4 are empty (as in the first case above), I prepend c.

So, the text a/b becomes ca/cb. And the text aa/b becomes aa/cb

I use the following regex for replacing:

(?(2)12|01)/(?(4)34|03)

But Notepad++ is treating ? literally in this case, and not as a conditional identifier. Any idea what am I doing wrong?

解决方案

The syntax in the conditional replacement is

(?{GROUP_MATCHED?}REPLACEMENT_IF_YES:REPLACEMENT_IF_NO)

The { and } are necessary to avoid ambiguity when you deal with groups higher than 9 and with named capture groups.

Since Notepad++ uses Boost-Extended Format String Syntax, see this 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 $1 was matched, and with 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

So, use ([a-zA-Z])([a-zA-Z])?/([a-zA-Z])([a-zA-Z])? and replace with (?{2}$1$2:c$1)/(?{4}$3$4:c$3).

The second problem is that you placed the ? quantifier inside the capturing group, making the pattern inside the group optional, but not the whole group. That made the group always "participating in the match", and the condition would be always "true" (always matched). ? should quantify the group.

这篇关于通过正则表达式在 Notepad++ 中替换时如何使用条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆