-1

Here's a small code, using python 3.4

import re
path_pattern=r'(([^\W]|[.~%$])+)'
re.search(path_pattern+'$','./').string

It will report AttributeError: 'NoneType' object has no attribute 'string' on execution.

If I remove the +'$' in the code, It works,

import re
path_pattern=r'(([^\W]|[.~%$])+)'
re.search(path_pattern,'./').string

As far as I know, $ is for matching the end of string, but why isn't it working here?

rox
  • 435
  • 4
  • 16

2 Answers2

2

If your explore your regex path_pattern at https://regex101.com/, you'll find it only matches ., so after you append $, it'll match nothing, and re.search returns None if no position in the string matches the pattern, that's why you get the error.

Check it out here:

>>> path_pattern=r'(([^\W]|[.~%$])+)'
>>> r = re.search(path_pattern + "$",'./')
>>> print(r)
None
shizhz
  • 9,521
  • 3
  • 33
  • 44
1

Your regex cannot match the / character in your string, and only . is matched.

When you use $ in your regex, it cannot match at all. When you remove it, it matches but only with ".".

Chuancong Gao
  • 574
  • 3
  • 7