r' question

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun May 18 05:04:03 EDT 2008


En Sun, 18 May 2008 02:49:03 -0300, Dick Moores <rdm at rcblue.com> escribió:

> However, (please refer back to my original post)
> I want to keep the fstr, ultimately to be the
> string entered by the user who knows a bit about
> regex, but not how to use r'  ' . Or
> alternatively, not assume any knowledge of regex,
> but build in some options, such as ignoring/not
> ignoring case, searching on just a string, or on
> a word. So I want to know how to build the user's
> fstr into regex. I apologize for not making this clear.

Ok, supose the user enters "joe (home)" and you want to build a regular expression to find that words surrounded by space:

fstr = "joe (work)"
regex = r"\s" + fstr + r"\s"

This doesn't work exactly as expected, because "(" and ")" have a special meaning in a regular expression; use re.escape:

regex = r"\s" + re.escape(fstr) + r"\s"

You may use "\\s" instead of r"\s", it's the *same* string. The r prefix is just a signal, it says how to interpret the source code, not part of the string.

-- 
Gabriel Genellina




More information about the Python-list mailing list