Getting to grips with regex in Perl -


i'm trying write regular expression match line:
dd month year @ hh:mm
example:
21 may 2009 @ 19:09

so have:
[0-30-9] day
[0-20-90-90-9] year
[0-90-9:0-90-9] time

i don't understand how put these form 1 single regex. want do

if($string =~ /myregex/) { }

but can't form entire thing. don't know how write regex month, has match 1 of 12 months of year.

i perl noob (this first day) , regex noob, appreciated!

well, parts have aren't quite correct. instead of [0-30-9] think mean [0-3][0-9], , other numbers.

however, suffices little looser , use \d equivalent [0-9].

you string parts 1 after other:

/\d\d (month) \d\d\d\d @ \d\d:\d\d/ 

which can written more succinctly as:

/\d\d (month) \d{4} @ \d\d:\d\d/ 

or if need more strict in formulation:

/[0-3]\d (month) [0-2]\d{3} @ \d\d:\d\d/ 

i've left month bit last, since more complicated bit. again can loose or strict.

loosely:

/[0-3]\d [a-za-z]+ [0-2]\d{3} @ \d\d:\d\d/ 

for strict match can use alternation, each alternative separated '|' , list of choices enclosed in parenthesis (although beware, parenthesis have meaning; don't worry won't interfere in case):

/[0-3]\d (january|february|march|april|may|june|july|august|september|october|november|december) [0-2]\d{3} @ \d\d:\d\d/ 

finally, if day not 0-padded (meaning 1st '1' rather '01') need make optional:

/[0-3]?\d (january|february|march|april|may|june|july|august|september|october|november|december) [0-2]\d{3} @ \d\d:\d\d/ 

crib sheet

  • [] used create character class, set of matching characters
  • \d built-in character class equivalent [0-9]
  • () used create group, useful delimiting alternation (amongst other things)
  • | used create alternation, list of alternative character sequences should matched
  • {n} modifier, saying 'n' of preceding character or character class should matched
  • + modifier, saying 1 or more of preceding character or character class should matched
  • ? modifier, saying 0 or 1 of preceding character or character class should matched

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -