#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    4
    Rep Power
    0

    Regular Expression matching and While Loops


    I get an infinite loop when doing the following:

    #[...] data prior
    import re
    r1 = re.compile('id.pmaptbl')
    while not(r1.search(mark)):
    mark = data[++i]
    #[...] data after

    I want the condition to exit when the r1.search(mark) thing doesn't get a match. Since the 're' stuff returns objects, I want to see if the r1.search(mark) gives me null. Since I am a newbie to Python, I have not found anything regarding objects and null. So I am guessing my logical NOT is no the right thing to use for re results.

    Any suggestions?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Posts
    136
    Rep Power
    11
    You have to see if re.search matches None:

    Code:
    if re.search(pattern, string) == None: print "regex didn't match string"

    an example:

    Code:
    >>> import re
    >>> p = re.compile("\d") # this will match any number
    >>> while 1:
    	s = raw_input("input: ")
    	if re.search(p, s) == None:
    		print "input not matching regex pattern. breaking out from the loop"
    		break
    	else:
    		print "input matched regex pattern"
    
    		
    input: 4343 fdfd
    input matched regex pattern
    input: fdf 4 fdfd
    input matched regex pattern
    input: 43
    input matched regex pattern
    input: fdsfdsfds
    input not matching regex pattern. breaking out from the loop
    >>>
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    35
    r1 = re.compile('id.pmaptbl')
    while not(r1.search(mark)):
    mark = data[++i]
    #[...] data after

    I want the condition to exit when the r1.search(mark) thing doesn't get a match.
    So you loop while it does get a match:

    Code:
    while r1.search(mark):
        mark = data[++i]
    However, what are you really trying to do? This looks somewhat ugly, and that can mean there's a neater way to do it...

    e.g.

    Code:
    while "id.pmaptbl" in mark:
        mark = data[++i]
    But what's in data?

    Since the 're' stuff returns objects, I want to see if the r1.search(mark) gives me null. Since I am a newbie to Python, I have not found anything regarding objects and null. So I am guessing my logical NOT is no the right thing to use for re results.
    If you don't specify a comparison in a test in Python, it defaults to "does this exist", so:

    Code:
    if x:
        print 1
    If x is bound to something, it will print 1, if x is not bound to anything (== None) then it wont. There's rarely a need to explicity compare things to None/null.

IMN logo majestic logo threadwatch logo seochat tools logo