3

Possible Duplicate:
What exactly do “u” and “r”string flags in Python, and what are raw string litterals?

p = re.compile(r'(\b\w+)\s+\1')

p.search('Paris in the the spring').group()

What is the meaning of r in the 1st line?

Community
  • 1
  • 1
Jack
  • 373
  • 1
  • 6
  • 14

2 Answers2

2

r designates a raw string in Python, which has different rules than a standard string, such as you don't have to escape backslashes and other special chars.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ajon
  • 7,868
  • 11
  • 48
  • 86
  • when using r why \w is still treated as escape sequence and not as literal. – Jack Nov 06 '12 at 04:45
  • As far as I know and in the documentation it doesn't say anything about \w being treated as an escape sequence. In fact it is not an escaped sequence. `\w` has no meaning. http://docs.python.org/2/reference/lexical_analysis.html#string-literals – ajon Nov 06 '12 at 05:18
  • You can check this link http://docs.python.org/2/howto/regex.html here it is mentioned about \w – Jack Nov 06 '12 at 05:48
  • Yes, `r"\w"` will match any alphanumeric character. Using r allows you to type `r"\w"` instead of `"//w"`. The r allows you to include Python Escape sequences inside of a string without needing to escape the \. I feel like I am not being clear to you. – ajon Nov 06 '12 at 06:51
  • thanks ajon. Now I understood in better way. – Jack Nov 06 '12 at 08:55
2

From the re documentation:

The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

Sam Mussmann
  • 5,883
  • 2
  • 29
  • 43
  • when using r why \w is still treated as escape sequence and not as literal ? – Jack Nov 06 '12 at 04:45
  • `\w` is not an escape sequence, it's a special sequence (towards the bottom of the [syntax section](http://docs.python.org/2/library/re.html#regular-expression-syntax) of the `re` documentation). – Sam Mussmann Nov 06 '12 at 18:07