-1

I am trying to make a regex code that will select from the second "ITEM1" to the first "ITEM2". Example:

ITEM1. text i don't want to find.
ITEM1.  text I want to find

ITEM2.  outside text

ITEM2 outside tex

Up until now, I came up with the following code:

(ITEM1)[\s\S]*?(ITEM2)

This select everythin from the first ITEM1 to the first ITEM2. I need the code to select between the second ITEM1 and the first ITEM2. Please let me know if you have any suggestions. Thank you in advance!!

Adrian
  • 774
  • 7
  • 26

1 Answers1

2

You can use

(?s)ITEM1(?:(?!ITEM1).)+?(?=ITEM2)

Start with ITEM1, lazily repeat characters that don't include the phrase ITEM1 (to ensure that only the second instance of ITEM1 gets matched), with lookahead for ITEM2.

match = re.search(r'(?s)ITEM1(?:(?!ITEM1).)+?(?=ITEM2)', str)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320