Question about regex grammar

I’m not sure about why the lowercase r is in the brackets for this simple regex code:


txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span() )

Are you referring to the r that prefixes the string literal? → r"\bS\w+"

The ‘r’ in a string construction, prevents the \ being interpreted as an ‘Escape’ character. It’s to do with ‘string literals’. It means, treat the string as a raw string.

This may be helpful

https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R' ; such strings are called raw strings and treat backslashes as literal characters. As a result, in string literals, '\U' and '\u' escapes in raw strings are not treated specially. Given that Python 2.x’s raw unicode literals behave differently than Python 3.x’s the 'ur' syntax is not supported.

Corresponding canonical on Stack Overflow:

This has nothing to do with regular expressions. This r prefix can be used for any string literal in the program, whether or not it’s used as a regular expression. It changes the rules that Python uses in order to understand what’s inside the quotes and create a string object. It does not change the rules that the standard library re module uses to understand the string object and create a regular expression object.