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!

matches and regexp 1

Status
Not open for further replies.

CherylD

Programmer
May 1, 2001
107
CA
Say I have a string:
" This is a sting 123-456"

I want to pull out the item at the end of the string which will always contain the charcter "-" with characters before and after it.

I need some help with the regexp on this....Any suggestions on where to start?
 
Here is one way to do it.

$str = " this is a string 123-456";

$str =~ /\s(\w+-\w+)\s*\Z/;

printf("result: %s\n",$1);

meanging:
\s = one space
(\w+-\w+) = one or more alphanumeric followed by - followed by one or more alpha numeric. () extracts that information. In this case to $1, further ()'s extract to incrementing numbers $2 $3 etc.
\s* = zero or more spaces
\Z = end of string.

So it finds your string starting with a space and ending with either an end of string, or spaces followed by end of string.

Sorry if I added more info than you need, but I didn't know how much you knew about regex already.

--
 
This quick reference guide is great for looking up the different things you can do in regexp, or any other perl stuff. Not much textual info, just a quick reference. But its enough for anyone that understands the concept and/or doesn't mind playing around with test files.

 
$string = "   This is a sting      123-456" =~ m/([0-9]+-[0-9]+)/;
print "matched : $1\n\n";

Cheers
Duncan
 
Hi duncdude,

I just have to point out, CherylD did say "characters" not numbers.

And she(?) did say at the end of the string.
So your example wouldn't work for say:

$string = " This is a sting with more info 4567-1283 123-456";
 
($var1, $var2) = split(/-/, $input);

That will split your string at the "-". If you wish to have it back you can always just do a;

$var2 = "-" . $var2;
 
$string = "   This is a sting with more info 4567-1283 123-456" =~ m/([\w]+-[\w]+)$/;

print "matched : $1\n\n";

Duncan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top