用于搜索和替换的正则表达式

时间:2009-06-24 16:01:57

标签: regex

我正在进行搜索和替换,需要替换逗号","的所有字符。

如何按任意顺序搜索所有字符?

例如:

string, like , this 

......将成为:

replace,replace,replace,

5 个答案:

答案 0 :(得分:4)

匹配任何非逗号字符:[^,] +

所以perl:s / [^,] + / replace / g

答案 1 :(得分:1)

在Perl中,您可以这样做:

my $string = "string, like , this";
my $replacement = "replace";
print $string, "\n";
$string =~ s/[^,]+/$replacement/g;
print $string, "\n";

答案 2 :(得分:1)

您应该将匹配的文本括在括号中,然后将其替换为例如搜索:

([^,]+)

然后替换:

\1

replace

答案 3 :(得分:1)

在vim中:

:%s/[^,]\+/replace/g

%            in the whole file
s            substitute
[^,]         match anything except comma
\+           match one or more times
/replace/    replace matched pattern with 'replace'
g            globally (multiple times on the same line)

答案 4 :(得分:0)

在红宝石中:

original = "string, like , this"
substituted = original.gsub(/[^,]+/, 'replace')
相关问题