Quick Python Regex Tip: Return True or False from a Python Regex Match

in #python6 years ago (edited)

thor.png

This is as much for me as a note for the future as it is a tip to share :)

In my scripts I had a problem where I was using the Python String .find() method.

This worked great unless the word you were looking for was commonly found within other common words.

As an example, I would look for "Thor" and find "Author" matched.

(Hence the silly photoshop above!)

For a long time I avoided Regex in Python because in my past with PERL and C# I had done enough of it for data validation that the thought made me roll my eyes into the back of my head.

Seems, however, Python's implementation is not as painful as I feared it would be.

While you can compile a regex object, like so:

re.compile("myregex.*")

You can also pass the regex to the search, saving me having to compile and recompile my regex for each keyword in my loop.

It also returns None or an object, which in an If statement does translate as True or False, but you can wrap it in Bool() if you need True or False returned.

Here is how my If turned out:

    if re.search(r"\b{}\b".format(needle), haystack, re.I):
            post_url = "/@{}/{}".format(author, permlink)

Here I am looking for my word (needle) surrounded by word boundaries in the returned sentence (haystack), ignoring case sensitivity.

So now I don't find authors when looking for Thor!*

Sort:  

Interesting post dear, i like it and enjoy it, thanks for sharing with us, keep it up. And im waiting for your next post. Thanks

Hmm, great works. Well i hope you find the authors soon

Nice, author in place fro Thor!

Although I don't know much about programming as I just got my hands on Python basics, I can sense that this is a point worth sharing. Thanks for the info☺️.

Congratulations @makerhacks, this post is the most rewarded post (based on pending payouts) in the last 12 hours written by a Superuser account holder (accounts that hold between 1 and 10 Mega Vests). The total number of posts by Superuser account holders during this period was 1131 and the total pending payments to posts in this category was $6651.29. To see the full list of highest paid posts across all accounts categories, click here.

If you do not wish to receive these messages in future, please reply stop to this comment.

Loading...

Coin Marketplace

STEEM 0.26
TRX 0.11
JST 0.032
BTC 63510.75
ETH 3065.54
USDT 1.00
SBD 3.82