Python Forum
Use or raw string on regular expressions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Use or raw string on regular expressions
#2
It is important to know that re uses its own parser to look at string expressions. Python passes a string or a raw string to re and re takes over.

Try this:

Quote:pattern = '\n'
pattern
'\n'
pattern = r'\n'
pattern
'\\n'

Whichever pattern you feed to re, re finds \n

. is a special character within re. \. is not a special character like \n

. represents, in re, any character except newline. If you feed '.' to re, you will get back all characters, but if you escape . as \. reu will just find the dot.

To quote the re docs:

Quote:Raw String Notation

Raw string notation (r"text") keeps regular expressions sane. Without it, every backslash ('\') in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are functionally identical:

re.match(r"\W(.)\1\W", " ff ")

re.match("\\W(.)\\1\\W", " ff ")
When one wants to match a literal backslash, it must be escaped in the regular expression. With raw string notation, this means r"\\". Without raw string notation, one must use "\\\\", making the following lines of code functionally identical:

re.match(r"\\", r"\\")

re.match("\\\\", r"\\")
Reply


Messages In This Thread
RE: Use or raw string on regular expressions - by Pedroski55 - May-09-2024, 06:26 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Information Do regular expressions still need raw strings? bobmon 3 468 May-03-2024, 09:05 AM
Last Post: rishika24
  Recursive regular expressions in Python risu252 2 1,585 Jul-25-2023, 12:59 PM
Last Post: risu252
Sad Regular Expressions - so close yet so far bigpapa 5 1,178 May-03-2023, 08:18 AM
Last Post: bowlofred
  Having trouble with regular expressions mikla 3 2,763 Mar-16-2021, 03:44 PM
Last Post: bowlofred
  Regular expression: cannot find 1st number in a string Pavel_47 2 2,497 Jan-15-2021, 04:39 PM
Last Post: bowlofred
  Regular expression: return string, not list Pavel_47 3 2,616 Jan-14-2021, 11:49 AM
Last Post: Pavel_47
  Regular Expressions pprod 4 3,263 Nov-13-2020, 07:45 AM
Last Post: pprod
  simple f-string expressions to access a dictionary Skaperen 0 1,601 Jul-15-2020, 05:04 AM
Last Post: Skaperen
  Format phonenumbers - regular expressions Viking 2 2,030 May-11-2020, 07:27 PM
Last Post: Viking
  regular expressions in openpyxl. format picnic 0 2,572 Mar-28-2020, 09:47 PM
Last Post: picnic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020