By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,330 Members | 1,112 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,330 IT Pros & Developers. It's quick & easy.

check if regeular expression has results

P: n/a
Hi,
I'm looking for the best way to check if regular expression return
true (it's mean - there is a match). for example, i want "if" that
check if this regular expression: .*born.*to.* has a match.

What's the way to do that simply?

Thanks a lot,
Shahar.

Aug 9 '07 #1
Share this Question
Share on Google+
3 Replies

P: n/a
On Thu, 09 Aug 2007 05:58:22 -0700, shahargs wrote:
I'm looking for the best way to check if regular expression return
true (it's mean - there is a match). for example, i want "if" that
check if this regular expression: .*born.*to.* has a match.

What's the way to do that simply?
Simply use an ``if`` on the result of the search or match. If the regular
expression doesn't match `None` is returned, which is `False` in a boolean
context, otherwise a match object is returned, which is `True` in a
boolean context.

Ciao,
Marc 'BlackJack' Rintsch
Aug 9 '07 #2

P: n/a
On 8/9/07, sh******@gmail.com <sh******@gmail.comwrote:
Hi,
I'm looking for the best way to check if regular expression return
true (it's mean - there is a match). for example, i want "if" that
check if this regular expression: .*born.*to.* has a match.

What's the way to do that simply?
How about

import re
re.match(".*born.*to", "This is a test")
re.match(".*born.*to.*", "This test was born so that it worked too.")

(Try these at the python prompt)

The first call to 're.match()' returns 'None' which will fail an if
test. The second one returns a match object, which evaluates to TRUE
in an if test.

--wpd
Aug 9 '07 #3

P: n/a
sh******@gmail.com wrote:
Hi,
I'm looking for the best way to check if regular expression return
true (it's mean - there is a match). for example, i want "if" that
check if this regular expression: .*born.*to.* has a match.

What's the way to do that simply?
A failed match returns None. A successful match returns a match object.
So the easiest way to check for a successful match is

pat = re.compile(...)
....
m = pat.match(some_string)
if m:
... you got a match ...
else:
... you didn't ...

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Aug 9 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.