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

ѕтƒ
  • 3,547
  • 10
  • 47
  • 78
  • 2
    `print ([sent for sent in test_str.split("\\n") if 'only for testing' in sent])` ([demo](https://rextester.com/RKBQ77131)) – Wiktor Stribiżew Dec 12 '19 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 `(.+?)` – MonkeyZeus Dec 12 '19 at 13:00
  • @MonkeyZeus : How will I do that? I'm new to regex – ѕтƒ Dec 12 '19 at 13:04
  • You should Google the steps I mentioned individually. Here's a start, https://stackoverflow.com/q/280435/2191572. Are you new to Python too? – MonkeyZeus Dec 12 '19 at 13:05
  • With regex, it will be a pain, see `re.findall(r'(?:^|\\n)((?:(?!\\n).)*only for testing(?:(?!\\n).)*)', test_str)` [demo](https://rextester.com/JISY46794) – Wiktor Stribiżew Dec 12 '19 at 13:16
  • Consider using raw strings (`r"foo"`) to prevent the blackslash plague. There is really no reason not to use raw strings when using regex with python. – Error - Syntactical Remorse Dec 12 '19 at 13:42
  • @WiktorStribiżew: Your first answer without using the regex should be good I guess. I will go for that. Thanks a lot Wiktor – ѕтƒ Dec 17 '19 at 12:53

1 Answers1

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())
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563