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

Regex search string with partial matches allowed

Suppose I have a search pattern like ^FOO.B.A.R, and I want to check whether a string matches the full search pattern, but, if the string is shorter than the search pattern, it’s allowed to match only part of it.

That is:

  • If the string is 1 character long, it must match ^F
  • If the string is 2 characters long, it must match ^FO
  • If the string is 3 characters long, it must match ^FOO
  • If the string is 4 characters long, it must match ^FOO.
  • If the string is 9 or more characters long, it must match ^FOO.B.A.R

Is there a way to specify this in the regex search pattern, or do I need to detect the length of the string and then build the pattern accordingly?

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

>Solution :

Probably the simplest way to solve this is to adjust the length of the pattern to match the input string, adding a $ to assert end-of-string for strings less than the length of the regex. You can then use re.match to test. For example:

regex = r'FOO.B.A.R'

strs = ['F', 'FOO', 'FOX', 'FOOYB', 'FOOYA', 'FOOXBYAZR', 'FOOBBAARRX']

for s in strs:
    pattern = regex[:len(s)] + ('$' if len(s) < len(regex) else '')
    print(f'{s}: {re.match(pattern, s) is not None}')

Output:

F: True
FOO: True
FOX: False
FOOYB: True
FOOYA: False
FOOXBYAZR: True
FOOBBAARRX: True
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