在两个字符串模式之间替换多次出现的字符 [英] Replacing multiple occurrences of a char between two string patterns

查看:51
本文介绍了在两个字符串模式之间替换多次出现的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下内容的文件 1.txt

I have a file 1.txt with below content

F1,F2,[as1,as2],[as3,as4]

F1,F2,[as1,as2],[as3,as4]

F3,F4,F5,[as5,as6]

F3,F4,F5,[as5,as6]

我需要在 perl 中编写一个正则表达式,以便我应该将 [' 和 '] 之间的分隔符 ',' 更改为 | .

I require to write a regex in perl so that I should change the delimiter ',' inbetween [' and '] to | .

我在下面尝试过,但没有奏效.

I tried below, but it did not work.

@qr = $st = /\{(.*)(\|)+\}/;

其中 $st 具有输入字符串.

where $st has the input string.

推荐答案

对于早于 Perl 5.14 的 Perl 版本,你不能不使用像这样的正则表达式

For the versions of Perl older than Perl 5.14, you can't but use a regex like

echo "[as1,as2,as3],[as4,as5]" | perl -lpe 's/(?:\[|\G(?!^))[^]]*?\K,/|/g'

查看在线演示.

模式详情:

  • (?:\[|\G(?!^)) - 文字 [ 或前一个匹配的结尾 (\G(?!^))
  • [^]]*? - 除 ] 之外的零个或多个字符,尽可能少地匹配
  • \K - 删除整个匹配值
  • , - 匹配中的逗号(被替换为 |).
  • (?:\[|\G(?!^)) - either a literal [ or the end of the previous match (\G(?!^))
  • [^]]*? - zero or more chars other than ], as few as possible, are matched
  • \K - the whole match value is dropped
  • , - a comma lands in the match (that is replaced with |).

对于 Perl 5.14 和更新版本(r 修饰符出现的地方),您可以将 [...] 子字符串与 \[[^][]+] 正则表达式(匹配 [,然后是除 [] 之外的 1+ 个字符,然后 ]) 并在这些匹配项中执行替换:

For Perl version 5.14 and newer (where r modifier appeared), you may match the [...] substrings with \[[^][]+] regex (that matches [, then 1+ chars other than [ and ], and then ]) and perform the replacements inside these matches:

echo "F1,F2,[as1,as2],[as3,as4]" | perl -lpe 's/(\[[^][]+])/$1=~s#,#|#gr/ge'
# => F1,F2,[as1|as2],[as3|as4]

查看在线演示.

这篇关于在两个字符串模式之间替换多次出现的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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