简体   繁体   English

如何在Perl中查找和替换正则表达式

[英]How to find and replace a regex in perl

我有一个文本,想要将所有\\w\\( ,例如myword(替换为一个空格,所以应该是myword ( 。如何用s/// ?或有另一种方法来做到这一点)。 ?

Try this 尝试这个

$s = "myword( word2(";
$s =~s/(\w+)(\()/$1 $2/g;
print $s;

As from @ikegami command. 从@ikegami命令开始。 My above regex \\w+ will backtrack this is needless. 我上面的正则表达式\\w+将回溯这是不必要的。 And no need to group the ( , because known one. So i changed my regex accordingly, 没必要组( ,因为已知的一个。因此我适时改变我的正则表达式,

New RegEx 新正则表达式

$s =~s/(\w)\(/$1 (/g;

Here is a way: 这是一种方法:

my $str = "myword(";
$str =~ s/(\w+)(\()/$1 $2/;
print $str, "\n";

Output: 输出:

myword (

Use look ahead: 使用前瞻:

$ perl -pe 's/(\w)(?=\()/$1 /' <<< 'word('
word (

Or look ahead together with look behind: 或一起向前看和向后看:

$ perl -pe 's/(?<=\w)(?=\()/ /' <<< 'word('
word (

Another way will be to use \\K ie forget what you matched before: 另一种方法是使用\\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+

or 要么

s/(\w)\(/$1 (/g

or 要么

s/(?<=\w)\(/ (/g

The first is much faster than the other two, but all are faster than the other correct solutions provided. 第一个比其他两个要快得多,但是都比提供的其他正确解决方案要快。 (Not sure which is the fastest of the second and third.) (不知道哪一个是第二和第三最快的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM