Javascript Regex Lookbehind Alternative

六眼飞鱼酱① 提交于 2019-12-20 07:28:43

问题


I want to catch word with non-space.

var paragraphy="Apple banana kişiler ki örnek foo.";
var word="kişiler"; 
var regex = new RegExp("(?:[\\s>]|^)("+word+")(?=[.,;?!]?(?:[<\\s])|$)", "gi");
console.log(paragraphy.match);

This prints: [" kişiler"] but I want this result: ["kişiler"] I must use Positive Lookbehind but it is not supported in JavaScript. Is there an alternative solution?


回答1:


Since you can't use word boundaries with unicode characters, let's match the spaces but group the word to retrieve it :

(?:^|\s)(<your word>)(?:\s|$)

After a match, group 1 should be the expected word.

For instance :

var regex = /(?:^|\s)(kişiler)(?:\s|$)/
var paragraphy="Apple banana kişiler ki örnek foo."
paragraphy.match(regex)[1]
> "kişiler"



回答2:


JS Demo

var paragraphy="Apple ba kişiler nana ki örnek foo.";
var word="kişiler"; 
var regex = new RegExp("(?:^|\\s)("+word+")(?=\\s|$)", "gi");
var m = regex.exec(paragraphy);
document.writeln(m[1]);


来源:https://stackoverflow.com/questions/36909848/javascript-regex-lookbehind-alternative

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!