regex question

Fredrik Lundh fredrik at pythonware.com
Fri Jan 21 03:48:41 EST 2000


Roy Smith <roy at popmail.med.nyu.edu> wrote:
> Let's say I've got a pattern "[0-9]", i.e. a 1-digit number.  I want to 
> search a string for that pattern, and only return a match if it's found 
> preceeded by either a non-digit or the beginning of the string, and 
> likewise followed by either a non-digit or the end of the string.  Is 
> there a single compact regex I can write to cover that?
> 
> For example:
> 
> pat = re.compile (pattern)
> x = pat.search ("1")
> y = pat.search ("12")
> z = pat.search ("the number 1, don't you know?")
> 
> x and z should be MatchObjects, but y should be None.
> 
> The best I can come up with would be something like:
> 
> (^[0-9][^0-9])|([^0-9][0-9][^0-9])|([^0-9][0-9]$)|(^[0-9]$)
> 
> which is fairly ugly.

umm.  speaking as the "official 1.6 regex implementor", I'd
go for a simple expression, and filter out any hits that are
not 12 digits.

haven't tried it, but I have a gut feeling that the resulting
code will be faster than any possible alternative...

(I'm happy to be proven wrong, of course)

</F>





More information about the Python-list mailing list