Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

c# - Regex search and replace where the replacement is a mod of the search term

i'm having a hard time finding a solution to this and am pretty sure that regex supports it. i just can't recall the name of the concept in the world of regex.

i need to search and replace a string for a specific pattern but the patterns can be different and the replacement needs to "remember" what it's replacing.

For example, say i have an arbitrary string: 134kshflskj9809hkj

and i want to surround the numbers with parentheses, so the result would be: (134)kshflskj(9809)hkj

Finding numbers is simple enough, but how to surround them?

Can anyone provide a sample or point me in the right direction?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In some various langauges:

// C#:
string result = Regex.Replace(input, @"(d+)", "($1)");
// JavaScript:
thestring.replace(/(d+)/g, '($1)');
// Perl:
s/(d+)/($1)/g;
// PHP:
$result = preg_replace("/(d+)/", '($1)', $input);

The parentheses around (d+) make it a "group" specifically the first (and only in this case) group which can be backreferenced in the replacement string. The g flag is required in some implementations to make it match multiple times in a single string). The replacement string is fairly similar although some languages will use 1 instead of $1 and some will allow both.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...