0

I want to create code which will return true if the string contains the word "post". So when I give my code string like "postgre", "postgres", "sqlpost" - it will return true. How can I do it?

1
  • 4
    You don't need a regular expression for that. Use if needle in haystack: (for appropriate values of needle and haystack). Commented Jun 2, 2015 at 21:00

2 Answers 2

2

You don't need regex for this. Just use the in operator:

>>> word = 'post'
>>> word in 'postgres'
True
>>> word in 'sqlpost'
True
>>> word in 'fish'
False
Sign up to request clarification or add additional context in comments.

Comments

1

If you care about matching exactly a word in a more elegant way than if ' post ' in mystring, you can use regex word boundaries which will enforce that your pattern only matches the word itself, not a substring within a word. For example,

>>> re.search(r"\bpost\b", "my post")
<_sre.SRE_Match object at 0x7fcb95165b28>
>>> re.search(r"\bpost\b", "my postgres")
>>>

matches post but not postgres.

Comments

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.