仅在正则表达式匹配项中替换字符 [英] Replace character in regex match only

查看:74
本文介绍了仅在正则表达式匹配项中替换字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在文本文件中搜索正则表达式,然后在匹配范围内仅将一个字符替换为另一个字符.我的问题是,我无法通过某些简单的方法来做到这一点.

I tried to search regex in textfile and than in match scope only replace one character by other. My problem is, that I'm unable to do it by some simple way.

示例源文件:

...
 <br>
<a id="some shopitem" ref="#some shop item name 01 a" style="text-decoration:none;"><h3 style="background-color: #ccc;">blah blab hasdk sldk sasdas dasda sd</h3></a>
<table>
 <td width="500">
....

我需要匹配正则表达式 ref = \#[[:: alnum:]] * \" (ref =#任何带有空格的名称"),然后将匹配的空格替换为"-",但当然不要更改其他空格或正则表达式匹配.

there I need to match regexp ref=\"#[[:alnum:] ]*\" (ref="#whatever name with spaces") and there replace spaces in match with "-", but of course do not change another spaces out or regex match.

因此结果应如下所示:

....
 <br>
<a id="some shopitem" href="#some-shop-item-name-01-a" style="text-decoration:none;"><h3 style="background-color: #ccc;">blah blab hasdk sldk sasdas dasda sd</h3></a>
<table>
 <td width="500">
....

在bash的单行命令中甚至不用某种脚本就能做到吗?有什么方法可以替换组中的空格吗?像 sed -r s/ref = \#([[:: alum:]] * \)/(\ 1s//-/g)/g'一样?

Would it be even possible to do it without some sort of script just in one-line command in bash? Is there some way how to replace spaces in group? something like sed -r s/ref=\"#([[:alnum:] ]*\)/(\1s/ /-/g)/g'?

推荐答案

Perl解决方案:

perl -pe 's/(ref="#)([\w\s]+)(")/ ($x,$y,$z)=($1,$2,$3); $y =~ s{\s}{-}g; $x.$y.$z /eg'

对于可以出现在引用名称中的内容(下划线、制表符、其他一些空白字符)稍微宽松一些

It's slightly more permissive about what can appear in the ref name (underscore, tab, some other whitespace chars)

这篇关于仅在正则表达式匹配项中替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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