Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Regex pattern match
#1
I am trying to match all characters between "\x" and "\xk" for instance: in the string "\x - \xo 2:2 \xk".

I set my pattern as:

pattern = "\\x.+\\xk"
replaceWith = "<b>"
irec=re.sub(pattern, replaceWith, irec)
However, this gives me an error in my replace. I also tried:
pattern = r"\x.+\xk"
replaceWith = "<b>"
irec=re.sub(pattern, replaceWith, irec)


But this gives same error: re.error: incomplete escape \x at position 0
Reply
#2
This is the double whammy. "\" is the start of an escape sequence for a str literal and it is the start of a special sequence in a regex pattern. Use one of these:
pattern = r"\\x.+\\xk"
pattern = "\\\\x.+\\\\xk"
You need the "\\x" to tell Python that the "\x" is not the start of a hex number. This makes the python str look like "\x.+\xk". But "\" in a pattern string is also meaningful, so we need another backslash to tell regex that we really want the characters '\' and 'x'.
Reply
#3
Thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Facing issue in python regex newline match Shr 6 1,147 Oct-25-2023, 09:42 AM
Last Post: Shr
  Failing regex, space before and after the "match" tester_V 6 1,116 Mar-06-2023, 03:03 PM
Last Post: deanhystad
  Match substring using regex Pavel_47 6 1,370 Jul-18-2022, 07:46 AM
Last Post: Pavel_47
  I need to copy all the directories that do not match the pattern tester_V 7 2,357 Feb-04-2022, 06:26 PM
Last Post: tester_V
  Match key-value json,Regex saam 5 5,299 Dec-07-2021, 03:06 PM
Last Post: saam
  regex pattern to extract relevant sentences Bubly 2 1,836 Jul-06-2021, 04:17 PM
Last Post: Bubly
  regex.findall that won't match anything xiaobai97 1 1,973 Sep-24-2020, 02:02 PM
Last Post: DeaD_EyE
  Creating new list based on exact regex match in original list interjectdirector 1 2,254 Mar-08-2020, 09:30 PM
Last Post: deanhystad
  regex match in a string batchen 4 3,161 Jan-20-2020, 08:48 AM
Last Post: batchen
  Regular expression: match pattern at the end only Pavel_47 3 1,827 Nov-27-2019, 07:51 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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