how to set variable to results of regex in one line

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
andersod2
Forum Newbie
Posts: 5
Joined: Sat May 02, 2009 1:15 am

how to set variable to results of regex in one line

Post by andersod2 »

Hi -- this is actually more of a perl question, but thought someone here might still know --

I want to be able to perform a regex match and set the results into a variable, but in one easy step rather than doing what I usually do, i.e.

if ( $matchstr=~ /(regex)/ ) {
$result = $1
}

I figure there is a better way than this right? I know I can do this with search/replace, but would like to preserve the original string.

...sorry if I'm missing something obvious....
User avatar
akuji36
Forum Contributor
Posts: 190
Joined: Tue Oct 14, 2008 9:53 am
Location: Hartford, Connecticut

Re: how to set variable to results of regex in one line

Post by akuji36 »

User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: how to set variable to results of regex in one line

Post by prometheuzz »

andersod2 wrote:Hi -- this is actually more of a perl question, but thought someone here might still know --

I want to be able to perform a regex match and set the results into a variable, but in one easy step rather than doing what I usually do, i.e.

if ( $matchstr=~ /(regex)/ ) {
$result = $1
}

I figure there is a better way than this right? I know I can do this with search/replace, but would like to preserve the original string.

...sorry if I'm missing something obvious....
AFAIK that is not possible and you will have to do it like you already mentioned in your post. But to be sure, I'd ask in a Perl forum if I were you: Perl has quite a few beat trick when it comes to regex and although I am familiar with PCRE, I'm far from a true Perl monk!

Good luck!
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: how to set variable to results of regex in one line

Post by prometheuzz »

I don't see how that is going to help the original poster...
Post Reply