[英]Substitute character not enclosed by brackets
I have a string containing curly brackets and I want to replace any character A, which is not contained in a pair of opening and closing brackets, by another character B. So 我有一个包含大括号的字符串,我想用另一个字符B替换任何在一对左右括号中都没有的字符A。
ABCDACD{ACDA}ABCD ABCDACD {ACDA} ABCD
should be replaced by 应该替换为
BBCDBCD{ACDA}BBCD BBCDBCD {ACDA} BBCD
How can I do this with a regex (eg in Perl)? 我该如何使用正则表达式(例如在Perl中)? Brackets are not nested, but a solution working also for the nested case would be better. 托架不是嵌套的,但也适用于嵌套案例的解决方案会更好。
EDIT: Changed wording 编辑:更改措辞
A similar question has already been answered before. 之前已经回答过类似的问题 。
Perl implementation will be different in substitution evaluation part but the main idea is the same: Perl的实现在替代评估部分将有所不同,但主要思想是相同的:
Match undesired context (ie {.*?}
) or desired substring ( A
) (in that particular order) using alternation capturing the matches. 使用交替捕获匹配项来匹配不需要的上下文(即{.*?}
)或所需的子字符串( A
)(以该特定顺序)。 Then substitute the undesired capture with itself and the desired one with your replacement depending on which part has matched: 然后,根据自己匹配的部分,将不想要的捕获替换为自己,并用所需的替换替换所需的捕获:
my $input = "ABCDACD{ACDA}ABCD";
$input =~ s/({.*?})|(A)/{$2 ? "B" : $1}/ge;
Demo: https://ideone.com/bK4c1Y 演示: https : //ideone.com/bK4c1Y
Here is a Perl solution that does the job in steps. 这是一个Perl解决方案,可以分步进行。 First it splits the string into chunks of braced/not braced items. 首先,它将字符串拆分为大括号/非大括号的项目。 Then does the substitution on the not-braced items, and finally puts the items back together again: 然后对不带括号的项目进行替换,最后将项目重新放在一起:
my $str = 'ABCDACD{ACDA}ABCD';
$str = do {
my $i = 1;
join '', map {$i++ % 2 && $_ =~ s/A/B/g; $_ } split /(\{.*?\})/, $str
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.