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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex question

Status
Not open for further replies.

capitano

Programmer
Jul 30, 2001
88
US
I want to use a regular expression to do the following:

$text =~ s/abc([.\s]+)abc/cba$1cba/g;

Essentially, I want to replace: abc(some text)abc
with: cba(some text)cba

So, I'm trying to use ([.\s]+) to move the (some text) into the substitution area with the standard $1.

However, this regex doesn't capture parentheses, or any other kind of puctuation. Is there a regex that is a "catch all" for alphanumerics, spaces, AND punctuations? ([.\s]+) obviously doensn't work.

Thanks,
Bryan
 
Use a '.' to match every character. Note that you also need to add a '?' to make the match non-greedy. The following should work:

$text =~ s/abc(.+?)abc/cba$1cba/g;
 
Right, a dot (.) inside of a character class ([]) isn't a wildcard... it's just a dot. Getting rid of the character class as raider2001 suggested should fix your problem.

As for the greediness, you have to decide what you want to do if you have a string like "abcxyzabcxyzabc". Do you want to match just "xyz" (non-greedy) or "xyzabcxyz" (greedy)?
Sincerely,

Tom Anderson
CEO, Order amid Chaos, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top