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

Getting the value of the matched text

Status
Not open for further replies.

milage

Programmer
Jul 13, 2001
58
US
Hi,

I have a string variable which I have done some pattern matching on and I want to assign the matched text to a new variable.

I have this:

$new_variable = $the_string =~ m/^\s*\w+/;

However, when the pattern is found this assigns 1 (true) to the new_variable rather than the string itself. How can i get it to assign the string?

Cheers
 
Code:
if ( $my_string =~ /(^\s*\w+)/ ) {
    $new_variable = $1;
}

Or something like that... Notorious P.I.G.
 
It looks as though your are trying to get rid of leading spaces. This is one way to do that:

($new_string = $old_string) =~ s/^\s*//;

Which would give you a copy of the old_string, minus the leading spaces. If you really want to capture stuff in your matches, you'll need to use capturing-parentheses:

$old_string =~ /^\s*[bold](\w+)[/bold]/;
$new_string = $1;
# capturing-parens store the
# matched text in $n variables, where n
# is a number indicating which paren-capture it is
# (you can have more than one set)

Or you could even use the g modifier and in list context, assign captures directly to variables:

($name, $number) = $entry =~ /(\w+)\s+(\d+)/g;

There's still more ways to get at the data matched... using $', $& and $`, using while-loops and the g-modifier, and more. That's called TMTOWTDI.

Cool huh?

--jim
 
OOps. I'm too slow. Started typing when no replies were up. Guess I need to learn how to type faster.;)

--jim
 
Good god. I wish you could go back and edit posts here.:

My seventh line in the previous*2 post should look like this:

$old_string =~ /^\s*(\w+)/;

Damnit.

--jim
 
That's ok, I almost just posted a foeach line in my last post. Caught it just before I hit submit...

*Edit buttons would be a real [thumbsup]* Notorious P.I.G.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top