Search code examples
pythonregexsearchattributeerror

Include '-' in regex search with \w+ . Python


k = 'a bunch of data and then name ""Serpin-ps""'        
print re.search(r'name\s""(\w+)""',k).group(1)

gives:

AttributeError: 'NoneType' object has no attribute 'group'

desired_output = 'Serpin-ps'

Makes sense because there is a '-' in the text.

Is there anyway to get regex to incorporate the '-' along with all the other alphanumeric characters?


Solution

  • You can put pre-set character classes like \w into explicit character classes. So:

    print re.search(r'name\s""([-\w]+)""',k).group(1)