[英]How to find and replace a regex in perl
我有一个文本,想要将所有\\w\\(
,例如myword(
替换为一个空格,所以应该是myword (
。如何用s///
?或有另一种方法来做到这一点)。 ?
尝试这个
$s = "myword( word2(";
$s =~s/(\w+)(\()/$1 $2/g;
print $s;
从@ikegami命令开始。 我上面的正则表达式\\w+
将回溯这是不必要的。 没必要组(
,因为已知的一个。因此我适时改变我的正则表达式,
新正则表达式
$s =~s/(\w)\(/$1 (/g;
这是一种方法:
my $str = "myword(";
$str =~ s/(\w+)(\()/$1 $2/;
print $str, "\n";
输出:
myword (
使用前瞻:
$ perl -pe 's/(\w)(?=\()/$1 /' <<< 'word('
word (
或一起向前看和向后看:
$ perl -pe 's/(?<=\w)(?=\()/ /' <<< 'word('
word (
另一种方法是使用\\K
即忘记之前匹配的内容:
#!/usr/bin/perl
use strict;
use warnings;
my $string = q{myword( myword2(};
$string=~s/\w\K\(/ (/g;
print $string,"\n";
s/\w\K\(/ (/g # 5.10+
要么
s/(\w)\(/$1 (/g
要么
s/(?<=\w)\(/ (/g
第一个比其他两个要快得多,但是都比提供的其他正确解决方案要快。 (不知道哪一个是第二和第三最快的。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.