-2

I wrote a function that verifies if a specific pattern exists in a given string:

import re
def has_pattern(string, regex):
    if string and re.compile(regex).search(string) is not None:
        return True
    return False

but for some reason my test doesn't show the expected result:

# for absolute path on windows
pattern = '^[a-zA-Z]:\\\\[^\\\\]' # actual regex: [a-zA-Z]:\\[^\\]
path = 'a:\\' # for this result should be 'True'
print('Pattern: \'{0}\''.format(pattern))
print('Result: {0}'.format(has_pattern(path, pattern)))
Matthew
  • 7,440
  • 1
  • 24
  • 49
neuronalbit
  • 358
  • 1
  • 3
  • 15

1 Answers1

2

Your pattern is looking for a letter (upper or lowercase) at the beginning of the string followed by a colon, a backslash, and then another character which is not a backslash.

Your testing input does not end in this non-backslash character, thus does not match the pattern.

One possible pattern adaption would be:

  • regex: ^[a-zA-Z]:\\(?:$|[^\\])
  • formatted for python string: ^[a-zA-Z]:\\\\(?:$|[^\\\\])
Matthew
  • 7,440
  • 1
  • 24
  • 49