Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a single regex for finding texts having at least one occurence of a certain type

The regex rule should find texts where "MyText" is not immediately followed by a numeric character on all occurrences. So what I need is to search whether a text has at least 1 occurrence of "MyText" without being followed by a numeric. I know how to do this using 2 regexes, but I would like to use a single regex.

import re 
def find_match(s):
    g1 = re.findall("MyText", s)
    g2 = re.findall("MyText[0-9_]", s)
    if len(g1) > len(g2):
        return True
    else:
        return False

Examples:

"MyText word1 word2" ✓

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"Something MyText335 blah blah blah" ⨉

"Blah blah MyText1" ⨉

"MyText something MyText02 something MyText123" ✓

>Solution :

You can use a negative lookahead 'MyText(?!\d)':

>>> re.search('MyText(?!\d)', "MyText word1 word2")
<re.Match object; span=(0, 6), match='MyText'>

>>> re.search('MyText(?!\d)', "Something MyText335 blah blah blah")
None
as a function:
import re 
def find_match(s):
    return bool(re.search('MyText(?!\d)', s))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading