Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Doubt in Regex Lookaround
#1
Hi

I am trying to use lookbehind for a sample code as below

import re
txt = "love regex or hate regex, can't ignore regex"
pattern = re.compile("(?<=(love|hate)\s)regex")
pattern.findall(txt)
The output of last line is ['love', 'hate']. But i am expecting the output to be['regex', 'regex'] at locations after love and hate.
Can you please check if i am missing something.
Reply
#2
Remove the catpuring group inside the regex
pattern = re.compile("(?<=(?:love|hate)\s)regex")
Reply
#3
Dear Gribouillis

Thanks a lot for your help. It works ok for me.
I have one more doubt. Can you plz look at it also

import re
txt = "T-STR(s)"
pat = re.compile(r"\bT-STR\(s\)\b", flags=re.IGNORECASE)
pat.findall(txt)
the output of the last line in above code is [], means an empty list,
but if i remove \b from the end, it matches to "T-STR(s)". This is strange to me as \b matches word boundaries than why issue with \b at the end.
Reply
#4
According to the documentation, \b matches between a \w and a \W character or a \w and one end of the string. It doesn't match between a ) and the end of the string.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Doubt about conditionals in Python. Carmazum 6 1,604 Apr-01-2023, 12:01 AM
Last Post: Carmazum
  A simple python doubt mohamedrabeek 2 727 Mar-26-2023, 07:24 PM
Last Post: deanhystad
  doubt about python tkinter and sqlite3 LONDER 2 2,153 Aug-14-2021, 08:48 AM
Last Post: ibreeden
  Python Doubt csrlima 5 2,602 Jan-23-2021, 12:23 AM
Last Post: csrlima
  Python Exercise Doubt azure 4 2,675 Apr-21-2020, 01:15 PM
Last Post: azure
  A doubt with 'in' and 'not in' operators with strings newbieAuggie2019 7 3,590 Oct-23-2019, 03:11 PM
Last Post: perfringo
  OpenCV - Doubt in a line. ArjunSingh 1 2,495 Jul-14-2019, 03:36 PM
Last Post: ThomasL
  doubt saipython 1 2,818 Aug-21-2017, 06:05 AM
Last Post: Larz60+
  Basic Doubt in code prateek3 6 4,913 Aug-19-2017, 01:05 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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