Reputation: 121
For example, I have sentence (str1) which have 2 word contractor and (str2) which have 1 contractor word. I need a regexp that will extract all sentences that contain 2 word contractor
var str1 = "Before hiring your chosen contractor, be certain to get a solid estimate in writing because not all contractors are honest and upfront in their quoting of costs."
var str2 = "Before hiring your chosen contractor, be certain to get a solid estimate in writing."
Upvotes: 1
Views: 351
Reputation: 16496
I defined a sentence as anything preceding a .
, ?
or !
here. Feel free to adapt to your needs.
To catch one contractor
:
[^.!?]*\bcontractor\b[^.!?]*[.!?]
Every match is a sentence with one or more "contractor" in it.
To catch two or more, use this:
[^.!?]*\bcontractor\b[^.!?]+\bcontractor\b.*?[.!?]
It reads aproximately as: match everything other than sentence ending, followed by the word "contractor", followed by more non-sentence-ending characters, followed by the word "contractor" again, followed by any chars and one sentence-ending-character.
Make sure to set the global g
flag, so that multiple matches per line can be found. You'll also have to trim the outcome since a sentence can begin with a white space in the pattern above.
Upvotes: 1