tags:

views:

191

answers:

5

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?

A: 

Depending on your language, you're looking to match groups.

So typically you'll make a pattern in the form of

([0-9]{1,})|([a-zA-Z]{1,})

Then, you'll iterate over the resulting groups in (specific to your language).

Noon Silk
+2  A: 

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.

gnarf
+1  A: 

Most regex replacement functions allow you to reference capture groups specified in the regex (a.k.a. backreferences), when defining your replacement string. For instance, using preg_replace() from PHP:

$var = "134kshflskj9809hkj";
$result = preg_replace('/(\d+)/', '(\1)', $var);

// $result now equals "(134)kshflskj(9809)hkj"

where \1 means "the first capture group in the regex".

Amber
+1  A: 
akf
+1  A: 

Backreferences (grouping) are not necessary if you're just looking to search for numbers and replace with the found regex surrounded by parens. It is simpler to use the whole regex match in the replacement string.

e.g for perl

$text =~ s/\d+/($&)/g;

This searches for 1 or more digits and replaces with parens surrounding the match (specified by $&), with trailing g to find and replace all occurrences.

see http://www.regular-expressions.info/refreplace.html for the correct syntax for your regex language.

libjack