might be an easy question but i’m fairly new to regular expressions.
given a paragraph, i would like to locate a particular sentence that begins with the specified word and replace the entire sentence with something else.
how can i build a regexp to search for a sentence that begins with a particular word, which can be followed by a number of different words, and ends with a . (period).
for example, given the sentence foo bar. foo3 bar3. foo2 bar2., find a substring that begins with foo3, has any number of words, and ends with ..
Something like this:
Searches for the period marking the previous sentence (or the beginning of the string in the case of the first sentence), followed by spaces, then the start character sequence (in this case,
foo3), followed by all non-period characters leading up to the period ending that sentence.Demo: http://www.rubular.com/r/ROl2odiDn5
Here’s how replacing the sentence might be implemented in practice:
In this example, I use the regular expression replace and incorporate the extra matched characters (period from previous sentence) via
$1, followed by the new sentence that is to replace the old sentence. This ensures that the state of the other sentences in the paragraph remains unchanged. Note also that this example will update all matching sentences, since I use the/g(global) flag. If you only want to change the first sentence, remove theg, or make your sentence matching more specific by including more beginning words.Demo: http://jsfiddle.net/qPxFp/2/