Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

regex meaning

by hashin_p (Initiate)
on Nov 12, 2007 at 10:22 UTC ( [id://650244]=perlquestion: print w/replies, xml ) Need Help??

hashin_p has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Could you detail on the regular expression $str =~ s/^0+(?=\d)// What is the meaning of the above? Thanks, Hashin

Replies are listed 'Best First'.
Re: regex meaning
by prasadbabu (Prior) on Nov 12, 2007 at 10:31 UTC

    Replacing the number starting with one or more zeros and followed by a number with none. Here (?=\d), is positive look ahead which has zero width assertion. So it ll replace only the zeroes and not the following number.

    Take a look at perlre and YAPE::Regex::Explain

    For example:

    $str = '004asdfsa'; #string starting with zero and followed by numbers $str =~ s/^0+(?=\d)//; print $str; Output: -------- 4asdfsa
    $str = 'a004asdfsa'; #not starting with zero $str =~ s/^0+(?=\d)//; print $str; Output: -------- a004asdfsa
    $str = '0a4sdfsa'; #no number followed by zero $str =~ s/^0+(?=\d)// ; print $str; Output: -------- 0a4sdfsa

    Prasad

      (I agree with what you say, but... I think a little simplification may be in order.)

      The reason for the lookahead (?=\d) is so it wouldn't replace a string "0000" with "", but with "0", by requiring at least one remaining digit.

      So the purpose is to strip leading zeros from strings that look like numbers, but leave a significant "0".

      Thank you very much..
Re: regex meaning
by oha (Friar) on Nov 12, 2007 at 10:32 UTC
  • ^ matches the start of the string
  • 0+ matches one or more zeroes
  • (?= followed by
  • \d a number

    it will substitute those zeroes with nothing. so it removes leading zeroes iff they are followed by a number

    Oha

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://650244]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-04-23 20:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found