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

a regexp problem

Status
Not open for further replies.

gremolin

Programmer
Oct 3, 2002
18
0
0
BG
Hi,
so, I want to do this:

I have a string like this 'a_word digit_1 digit_2'
a_word is always required, digit_2 cannot be there without digit_1
I have a three states of string:
1 - 'a_word'
2 - 'a_word digit_1'
3 - 'a_word digit_1 digit_2'

I want to use a regular expression to catch a_word -> $1, digit_1 -> $2, digit_2 -> $3
I try to use $str =~ /^(\w+)(\s+(\d+))*(\s+(\d+))*$/;
$1 $2 $3
when string is on 1st state there is no problems.
when is 2nd $3 and $2 catch the value of digit_1.
on 3th state $2 and $3 catch the value of digit_2.

Can you advice me how to change my regexp by way that guarantee to me that if some value of digit_p is missing the relevant $x will be undef.

10q
 
You don't need (or want) to capture the spaces, just make them 'zero-or-more' matches rather than 'one-or-more'.
Code:
$str =~ /^(\w+)\s*(\d+)?\s*(\d+)?$/;
jaa
 
I try this and it is OK now, thank you.
I was scared that if a_word -> some1 that 1 will become $2.
But this state will never happen in a_word.
 
I was scared that if a_word -> some1 that 1 will become $2

This wouldn't happen because the '\w+' is greedy, meaning that it matches everything up to the point that it doesn't match. So it will keep matching 'word' characters until it runs into a non-word character and capture them all. If you were to make it non-greedy, '\w+?', then you would have this problem if there were no other digits or just digit_1 (if digit_1 and digit_2 are present then both \d+'s have to match their digits and \w+ can keep its digits).

In this way regexes (and most of Perl) employs a DWIM (Do What I Mean) strategy. Thing will work the way you expect them to unless you force them not to.

jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top