-2

I need help with very simples question, a conditional using regex with multiline string. No make sense to me why this not work:

if(re.match(r"\w", " \n\n\n  aaaaaaaaaaaa\n\n", re.MULTILINE)):
    print('ok')
else:
    print('fail')

fail

I expected that result be ok, but no match any data. I trying using https://regex101.com/r/BsdymE/1, but there works and in my code not works.

Błotosmętek
  • 12,717
  • 19
  • 29
Luiz Carvalho
  • 1,549
  • 1
  • 23
  • 46

2 Answers2

1

re.match will only return a match if the search string is at the beginning.

https://docs.python.org/3/library/re.html#re.match

re.match(pattern, string, flags=0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Try using re.search(pattern, string, flags=0) instead

Community
  • 1
  • 1
wski
  • 305
  • 1
  • 10
0

From pydoc re.match:

Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found.

(emphasis mine). So, the problem is not with the string being multiline, but rather with it not beginning with a word-class character. If you want to check if a string contains something anywhere, use re.search instead.

Błotosmętek
  • 12,717
  • 19
  • 29