这是您想要的正则表达式:
/\s?([^\s]+\swelcome\s[^\s]+)\s?/i //very simple, no a strange bunch of [] and {}
解释:
你试图匹配的实际上是
《世界,欢迎来到》
前后没有空格,因此:
\s? //the first space (if found)
( //define the string position you want
[^\s]+ //any text (first word before "welcome", no space)
\s //a space
welcome //you word
\s //a space
[^\s]+ //the next world (no space inside)
) //that's it, I don't want the last space
\s? //the space at the end (if found)
申请:
function find_it(p){
var s = "Hello world, welcome to the universe",
reg = new RegExp("\\s?([^\\s]+\\s" + p + "\\s[^\\s]+)\\s?", "i");
return s.match(reg) && s.match(reg)[1];
}
find_it("welcome"); //"world, welcome to"
find_it("world,"); //"Hello world, welcome"
find_it("universe"); //null (because there is no word after "universe")