Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to extract whole sentences with matching word

Tags:

regex

I would like to extract sentences with the word "flung" in the whole text.

For example, in the following text, I'd like to extract the sentence "It was exactly as if a hand had clutched them in the centre and flung them aside." using regular expression.

I tried to use this .*? flung (?<sub>.*?)\., but it starts searching from the beginning of the line.

How could I solve the problem?

As she did so, a most extraordinary thing happened. The bed-clothes gathered themselves together, leapt up suddenly into a sort of peak, and then jumped headlong over the bottom rail. It was exactly as if a hand had clutched them in the centre and flung them aside. Immediately after, .........

like image 754
DanEng Avatar asked Sep 28 '14 05:09

DanEng


People also ask

How do I match an entire line in regex?

To expand the regex to match a complete line, add ‹ . * › at both ends. The dot-asterisk sequences match zero or more characters within the current line.

Which regex matches the whole words dog or cat?

If we want to improve the first example to match whole words only, we would need to use \b(cat|dog)\b. This tells the regex engine to find a word boundary, then either cat or dog, and then another word boundary.

How do you use regex to find a sentence?

The regex operation “^. *?.?!;” can be used to search for the first sentence in the text. The expression basically returns all the text before a period, question mark, exclamation mark, or a semicolon, that follows an empty white space. Here is an example script that can be used to return the first sentence in a text.

What does \f mean in regex?

\f stands for form feed, which is a special character used to instruct the printer to start a new page.


1 Answers

Here you go,

[^.]* flung [^.]*\.

DEMO

OR

[^.?!]*(?<=[.?\s!])flung(?=[\s.?!])[^.?!]*[.?!]

DEMO

like image 194
Avinash Raj Avatar answered Oct 18 '22 08:10

Avinash Raj