加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

排除正则表达式匹配中的字符串,用于sed处理

发布时间:2020-12-14 05:55:50 所属栏目:百科 来源:网络整理
导读:我需要匹配这个替换命令: whatever__MATCH_THIS__whateverwhatever__AND_THIS__whateverwhatever 我正在尝试: sed -e 's/__(.*)__/{{1}}/g' myfile 但这是热切地匹配__MATCH_THIS__whateverwhatever__AND_THIS__,产生: whatever{{MATCH_THIS__whateve
我需要匹配这个替换命令:

whatever__MATCH_THIS__whateverwhatever__AND_THIS__whateverwhatever

我正在尝试:

sed -e 's/__(.*)__/{{1}}/g' myfile

但这是热切地匹配__MATCH_THIS__whateverwhatever__AND_THIS__,产生:

whatever{{MATCH_THIS__whateverwhatever__AND_THIS}}whateverwhatever

但我想:

whatever{{MATCH_THIS}}whateverwhatever{{AND_THIS}}whateverwhatever

如何在匹配部分中指定要排除的字符串?我知道如何排除一个字符(例如[^ a])但不知道如何排除字符串.

解决方法

你需要的是一个非贪婪的正则表达式,但不幸的是sed不允许这样做.但是,它可以在perl中完成.

perl -pe 's|__(.*?)__|{{$1}}|g' <myfile

星号后面的问号表示匹配器是非贪婪的,所以不是采用它能找到的最长的匹配字符串,而是最短的.

希望有所帮助.

如果你想把它放在一个perl脚本而不是在命令行上运行,那么这样的事情就可以完成这项工作:

#! /usr/bin/perl -w
use strict; # Habit of mine
use 5.0100; # So we can use 'say'

# Save the matching expression in a variable. 
# qr// tells us it's a regex-like quote (http://perldoc.perl.org/functions/qr.html)
my $regex = qr/__(.*?)__/;

# Ordinarily,I'd write this in a way I consider to be less perl-y and more readable.
# What it's doing is reading from the filename supplied on STDIN and places the
# contents of the file in $_. Then it runs the substitution on the string,before
# printing out the result.
while (<>) {
  $_ =~ s/$regex/{{$1}}/g;
  say $_;
}

用法很简单:

./regex myfile
whatever{{MATCH_THIS}}whateverwhatever{{AND_THIS}}whateverwhatever

这是Perl,有一百万种方法可以做到!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读