Python Forum
regular expression for a transformation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
regular expression for a transformation
#1
Hi

I cannot work out why the following works:

import re
text = "Follow up on the new sales *order*. Do not consider the cancelled *order*"
pattern = re.compile(r'\*(.*?)\*')
print("Before substitution: ", text)
text = pattern.sub(r"<b>\g<1><\\b>", text)
print("After substitution: ", text)
but the following generates a "bad escape \g" error:

import re
text = "Follow up on the new sales *order*. Do not consider the cancelled *order*"
pattern = re.compile(r'\*(.*?)\*')
print("Before substitution: ", text)
transform_pattern = re.compile(r"<b>\g<1><\\b>")
text = pattern.sub(transform_pattern, text)
print("After substitution: ", text)
Any suggestions?
Thanks
Reply
#2
Well, the reason is that \g is not a valid escape sequence... Big Grin

Seriously, in the line:
text = pattern.sub(r"<b>\g<1><\\b>", text)
The r-string is not a regex, is used as a raw-string, to avoid the backslash hell... otherwise you need to use "<b>\\g<l><\\\\b>".
This is more evident if you do not split the compile and the sub phases:
#      re.sub(pattern, replacement, text)
text = re.sub(r'\*(.*?)\*', r"<b>\g<1><\\b>", text)
In your second example you are trying to interpret '<b>\g<1><\\b>' as a regular expression:
transform_pattern = re.compile(r"<b>\g<1><\\b>")
And in that context \g is not valid.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  point transformation software in space johnjsi 2 388 Feb-01-2024, 01:31 AM
Last Post: johnjsi
  data validation with specific regular expression shaheen07 0 338 Jan-12-2024, 07:56 AM
Last Post: shaheen07
  Regular Expression search to comment lines of code Gman2233 5 1,666 Sep-08-2022, 06:57 AM
Last Post: ndc85430
  List Creation and Position of Continue Statement In Regular Expression Code new_coder_231013 3 1,666 Jun-15-2022, 12:00 PM
Last Post: new_coder_231013
  Need help with my code (regular expression) shailc 5 1,924 Apr-04-2022, 07:34 PM
Last Post: shailc
  Regular Expression for matching words xinyulon 1 2,176 Mar-09-2022, 10:34 PM
Last Post: snippsat
  regular expression question Skaperen 4 2,485 Aug-23-2021, 06:01 PM
Last Post: Skaperen
  How can I find all combinations with a regular expression? AlekseyPython 0 1,676 Jun-23-2021, 04:48 PM
Last Post: AlekseyPython
  Python Regular expression, small sample works but not on file Acernz 5 2,933 Jun-09-2021, 08:27 PM
Last Post: bowlofred
  Calculate transformation and Rotation Sandra2312 1 1,809 Jan-31-2021, 12:53 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

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