1

I have a list of words (even 2 or 3 words in 1 object) . I have compiled a regex to match any of the words in the list to a random string . If it matches , that object of the list is returned ,else it will execute another regex on the string to return an expression.
my code:
"layouts" is the list of words and "layout_re" uses the words in list to match in the string "str". If ms is present in list , return ms as it is otherwise use expression of p to return the pattern.

def layout_corr(str):

    ms = layout_re.search(str)
    if ms in layouts:
       ms=ms

    else:
       p = re.compile(r'(?:\w+\s+){1,2}layout')
       ms = re.findall(p,str)
    return ms

The output i get is that of the else statement .
eg:- str = " no 804 8th main 2nd c cross hrbr layout 1st block"
the list contains "hrbr layout" hence hrbr layout must be returned. But instead , the function returns "cross hrbr layout" which is the ms calculated by else statement.. What is the problem with the if statement??

1
  • 1
    re.search returns a match object (or None), while re.findall returns a list. Neither one returns purely object matched. Commented Mar 6, 2014 at 5:42

2 Answers 2

1

re.search returns a match object, not a string, so that:

ms in layouts

will always return false. Use this instead:

def layout_corr(str):
    ms = layout_re.search(str)
    if ms:
       return ms.group()    
    else:
       p = re.compile(r'((?:\w+\s+){1,2})layout')
       ms = re.findall(p,str)
       return ms
Sign up to request clarification or add additional context in comments.

2 Comments

You could use (\w+(?:\s+\w+)?)\s+layout for the second regex, if you want to trim spaces.
Also, you should avoid using str since it's a function name (already told you in chat, but mentioning it here too)
0

1) change ms=ms to return ms

2) In order to "catch" the string "hrbr layout" - change the line:

p = re.compile(r'(?:\w+\s+){1,2}layout')

to:

p = re.compile(r' (\w+? layout)')

Demo:

p = re.compile(r' (\w+? layout)')
ms = re.findall(p,"no  804  8th main 2nd c cross hrbr layout 1st block")
print(ms[0]) // prints: "hrbr layout"

2 Comments

hrbr is in list. if i use this expression then it will extract 1 word before layout always.. what i want is to check presence in the list called"layouts" and return the same if present.. If not , then return 2 words before layout.. Hrbr is in the layouts list , so i want the 1 st statement to return the exprssion
@Sword in that case change ms=ms to return ms

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.