2

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

7
  • 2
    print ([sent for sent in test_str.split("\\n") if 'only for testing' in sent]) (demo) Commented Dec 12, 2019 at 12:57
  • If you're insisting on a Regex solution then you need to escape your search term for use in regex and then interpolate that string within (.+?) Commented Dec 12, 2019 at 13:00
  • @MonkeyZeus : How will I do that? I'm new to regex Commented Dec 12, 2019 at 13:04
  • You should Google the steps I mentioned individually. Here's a start, stackoverflow.com/q/280435/2191572. Are you new to Python too? Commented Dec 12, 2019 at 13:05
  • With regex, it will be a pain, see re.findall(r'(?:^|\\n)((?:(?!\\n).)*only for testing(?:(?!\\n).)*)', test_str) demo Commented Dec 12, 2019 at 13:16

1 Answer 1

2

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())
Sign up to request clarification or add additional context in comments.

Comments

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.