I have a rich text like
Sample text for testing:<a href="http://www.baidu.com" title="leoshi">leoshi</a>leoshi for details balala...
Welcome to RegExr v2.1 by gskinner.com, proudly hosted by Media Temple!
What I want to match is the word leoshi
, but not inside of <a>
elements, So in this example it's only leoshi
in leoshi for details....
Solution and explanation are welcome!
A trick aimed to handle such "find a word but not a specific context" cases is described here: http://www.rexegg.com/regex-best-trick.html.
In essence it is: match your word in the undesired context or (using alternation) just this word but in a capture group. Then analyze the captures.
The regex in your case would be:
<a.*?>.*leoshi.*<\/a>|(leoshi)
Demo: https://regex101.com/r/zO0tV2/1
Then you need to check captures:
var input = "...";
var pattern = /<a.*?>.*leoshi.*<\/a>|(leoshi)/;
var match = pattern.exec(input);
var inputMatches = match !== null && match[1] !== null;
Demo: https://ideone.com/KkAl2I