简体   繁体   中英

javascript regexp find particular sentence

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. foo bar. foo3 bar3. foo2 bar2. , find a substring that begins with foo3 , has any number of words, and ends with . .

Something like this:

/(^|\.\s+)(foo3[^.]*\.)/

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:

var str = "foo bar. foo3 bar3. foo2 bar2.";
var regex = /(^|\.\s+)(foo3[^.]*\.)/g;
str = str.replace(regex, "$1new sentence.");
alert(str);

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 the g , or make your sentence matching more specific by including more beginning words.

Demo: http://jsfiddle.net/qPxFp/2/

shortest/most-efficient I can think of:

/foo3\b[^.]*\./

However, that has a few problems:

  • it will match up to a decimal number (like matching foo3 contributed $4. from foo3 contributed $4.83 million to the campaign.
  • it will technically match foo3 anywhere in a sentence to the end of the sentence (like matching foo3's guts. in I hate foo3's guts. )
  • it won't allow for sentences ending in exclamation points or question marks, for example

The following expression fixes these things - though it's a bit less efficient (by requiring some sort of whitespace or end-of-string after the punctuation):

/(^|[.!?]\s+)foo3\b.*?(?=[.!?](\s|$))[.!?]/

...replace with eg: $1Replacement sentence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM