开发者

Replacement in regular expression

开发者 https://www.devze.com 2023-02-16 21:26 出处:网络
I have a list: 1name1 2name2 3name3 I need to replace all 1,2,3... to \'1\', \'2\', \'3\'...and name1, name2, na开发者_StackOverflow中文版me3 to \'name1\', \'name\', \'name\'3.

I have a list:

1  name1
2  name2
3  name3

I need to replace all 1,2,3... to '1', '2', '3'...and name1, name2, na开发者_StackOverflow中文版me3 to 'name1', 'name', 'name'3. I know how to do it via '\n' and '\s'.

But I think the better way exists. Does anybody know this way?


Here is a JavaScript solution:

str = str.replace(/(\w+)/g, "'$1'");


you can do it easily with perl,

on a unix machine, from the terminal:

perl -pe 's/regex/replace/' input > output

(the > output is optional, and it will just get printed to the terminal)

so:

perl -pe "s/([0-9]+)\s(.*)/'\1' '\2'/g" file > file2

That will find at least one number at the beginning, and capture it (as \1). then some white space, then the rest of the line, captured (as \2). the after the / is the replace bit. just add in the ' s and insert the captured bits.

(if you're on windows, you can get perl here: http://www.perl.org/get.html#more)


Heres a little snippet in PHP:

$str = "1 name1\n2 name2\n3 name3";
$str2 = preg_replace('!([^\s]+)\s([^\n]+)!sm', "'$1' '$2'", $str);
echo $str2;

It uses $1 and $2 to reference the rounded bracket you 'catched' in the string

0

精彩评论

暂无评论...
验证码 换一张
取 消