Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regular Expression Question (insertion/substitution)

Status
Not open for further replies.

MaxCarp

Programmer
Aug 16, 2011
5
US
Basically, I am trying to construct a substitute expression that accomplishes the following: given all occurrences of a certain type of string (for instance, digits), insert some prefix or suffix before or after all occurences.

For example, in the string --12***345)))6789?<>, I want to insert some prefix before the numeric substrings, to give e.g. --found12***found345)))found6789?<>

Now, the regular expression

s/[0-9]*/found/g would find all strings of digits and replace them with the word "found." However, I want to keep the substrings of numbers and insert a prefix. What do I need to do?

Thanks, Max
 
The easiest way to do what you're looking for is something similar to:
Code:
$_ = '--12***345)))6789?<>';
my $prepend = $_;
$prepend =~ s/(\d+)/found${1}/g;
print "$prepend\n";
my $append = $_;
$append =~ s/(\d+)/${1}found/g;
print "$append\n";
For more information, take a look at: perldoc perlre
 
Thank you.

Sorry for the naive question, but if I understand it correctly, the construct ${1} means taking a single instance of the regular expression and assigning it to the substring ${1}?
 
You're welcome.

$1 (${1} is a different way to notate the same thing that helps differentiate the variable name from any other characters immediately after the variable) refers to the first capture group.

Here's a link to the pertinent section in perldoc perlre I mentioned above. perlre - Capture Groups

I would really suggest you take some time and read through that perlre perldoc page. A lot of it won't make sense initially but it will give you a good idea about how the regex engine works and how to construct regexs to do what you want.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top