Friday 15 August 2014

javascript - Could anyone explain what's wrong with my regex? -


I have a small regex question. In one sentence, I would like to match one or several words and the only characters allowed before and after this are also called an alternate space character.

Example: Sufficient time to use in sentence. I do not want to match the volutpat and not the volutpat As long as I'm looking for volutpat Especially.

Here is the code ():

  var sentence = 'now'. ', Word =' ​​voltpat ', regesx = new regx (' [ss]? '+ Word +' [\ s]? ',' G '); Console.log (sentence.match (regex));   

Unfortunately in the console, the code above the two matches:

  ["volutpat", "volutpat"]   

Please note that, word = 'voltpat egesa' or word = 'wolfpat.' should also work, if I have to match them.

Dynamically creating regular expressions, you should keep in mind that to avoid any backslash Required:

  Var Sentence = 'Uuppullup Egase Vertiput.', Word = 'voltipt', reggix = new regx ('[\\ s]?' + Word + '[\\ s ]? ',' G ');   

In addition, you might want to check space-or-start-or-end, not space-alternatively, so:

  Var sentence =, "word", "word", "regex = new regepx" ("(^ | \\ s) '+ word +' (\\ s | $) ',' g ');   

Assume that does not win the word , you may want to see it in it too.

No comments:

Post a Comment