Confusion with ? in Regular expression

This is the place for queries that don't fit in any of the other categories.

Confusion with ? in Regular expression

Postby deathmetal » Tue Apr 09, 2013 4:04 am

Hi Forum Members,
I am trying to write a code using regular expression using ?. However, I am unable to understand why my given string doesn't match as expected

pattern='cold?est'
s1='cest'
s2='coest'
s3='colest'
s4='coldest'

when searched using re.search(pattern, s3), re.search(pattern, s4)
It works fine, but it doesn't work with s1 and s2. I cannot understand why, as ? means occurrence of preceding characters once. Here those characters can be anything between c o l d.
On the contrary it matched l d ONLY :!:
deathmetal
 
Posts: 6
Joined: Mon Apr 08, 2013 3:05 pm

Re: Confusion with ? in Regular expression

Postby setrofim » Tue Apr 09, 2013 5:37 am

deathmetal wrote: as ? means occurrence of preceding characters once

No it doesn't. ? means "match the preceding character (singluar!) exactly zero or one times", which what it is doing -- matching 'd' zero or one times. (Technically, I should probably say "preceding element" rather than " preceding character", as it could be a character, a group or a range -- but it is always one thing.)

To get the bahavior you want, you could do something like
Code: Select all
pattern = '[cold]*est'

Which means "match characters 'c', 'o', 'l' or 'd' zero or more times, followed by 'est'". This however, will also match strings like 'cccccccest' or 'doclest'. If you only want to mach the examples given, then it'd be something like
Code: Select all
patter = 'c(o|ol|old)?est'

i.e. "match 'c' followed by either 'o', 'ol' or 'old' zero or one times, followed by 'est'.

I suggest you go through this.
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: Confusion with ? in Regular expression

Postby deathmetal » Tue Apr 09, 2013 10:48 am

@ setrofim
Thank you very much for clearing this to me. I misinterpreted. :|
Hardly there can be a crystal-clear explanation than yours. :)
The URL you shared, is a nice one. I will try to learn as much as possible from it. Thank you once again.
deathmetal
 
Posts: 6
Joined: Mon Apr 08, 2013 3:05 pm


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot] and 7 guests