2

I have been trying to get text between two strings-('Item' and 'Item') but since 'Item' is present multiple times throughout the large document(which is itself a string) i get almost all whole of the document. I can't figure out the regex code to get text between one 'item' and the next 'Item' till the last 'Item' as different strings.

I have tried regex codes but i can't figure it out.

First try :

(?<=Item)(.*)(?=Item)

Second try:

value = search('Item(.+)Item', text)
if value is not None:
    value = value.group(1)

The First try selects almost all of document

The Second try only gives the first occurrence of text between 'Item' and 'Item'.

Any help would be greatly appreciated.

8
  • 1
    Try making it non greedy. Since you capture the value in a group, you can omit the lookarounds. Item(.*?)Item Commented May 29, 2019 at 11:47
  • Could you give sample text and expected result? Commented May 29, 2019 at 11:53
  • Sample Text: 'Item Hello this is a sample Item String on StackOverflow Item Posted on a Item Wednesday' . Result: Hello this a sample , String on Overflow, Posted on a , Wednesday Commented May 29, 2019 at 11:56
  • @Thefourthbird I tried doing that but it sill returns only the first occurrence Commented May 29, 2019 at 12:02
  • 1
    @Thefourthbird Thanks for your help too! I now understand the logic behind it Commented May 29, 2019 at 12:19

1 Answer 1

1
import re

string = 'Item Hello this is a sample Item String on StackOverflow Item Posted on a Item Wednesday'

print re.findall(r"(?<=Item ).+?(?= Item|$)",  string)

Output:

['Hello this is a sample', 'String on StackOverflow', 'Posted on a', 'Wednesday']

Explanation:

(?<=Item )      # positive lookbehind, make sure we have "Item " before
.+?             # 1 or more any character, not greedy
(?= Item|$)     # positive lookahead, make sure we have "Item " or end of line after
Sign up to request clarification or add additional context in comments.

1 Comment

This worked ! Thank you @Toto . I am new to regex but i definitely have learnt a new useful method!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.