ѕтƒ
ѕтƒ

Reputation: 3647

Regular expression to get substring from a string

consider I have a string as following,

\n this is a paragraph. please ignore  \n this is a only for testing. please ignore \n

I have a search word as "only for testing". and I want to get the sentence which contains "only for testing" with in the \n the search word resides. In this case the output will be this is a only for testing. please ignore.

If I give paragraph as search word I should get the output as

this is a paragraph. please ignore

I have tried

test_str = "\\n this is a paragraph. please ignore  \\n this is a only for testing. please ignore \\n"
pattern = re.compile("\\\\n(.+?)\\\\n")
match = pattern.findall(test_str)

But not working as expected

Upvotes: 2

Views: 76

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

You may use a solution without a regular expression:

result = [sent for sent in test_str.split("\\n") if 'only for testing' in sent]

See the Python demo

Details

  • test_str.split("\\n") - split the text by \n
  • if 'only for testing' in sent - only keep the items that contain only for testing (for a case insensitive comparison, use if 'only for testing' in sent.lower())

Upvotes: 2

Related Questions