Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

How to exclude Regex matches from inside urls with JavaScript

My current regex looks for a searchQuery inside sentences and matches them if those queries start a with a blank space, and end with either a blank space or ?!,.. It generally works well, except for URLs. The regex ends up picking up urls and messing them up.

For example, if I was looking for "bitcoin" in a sentence "Bitcoin price is going nuts", it would find it, but it was also take the following url and match it. https://versionone.vc/the-solar-bitcoin-convergence, messing up the url.

How can I tell JavaScript Regex to ignore any matches where the character before the matching words is either of these / - . _ + ? This will essentially eliminated matches inside urls?

Current Regex: var reg = new RegExp('(\b)${searchQuery}(\s+|\.|\,|\?|\!', 'gi');

Replacement function: newString = oldString.replace(reg, substringReplacement);

substringReplacement(match) is a function that contains the logic of how to change the matching text.

Alternatively, what's another way to outright ignore urls from the searchable area. Thanks!

question from:https://stackoverflow.com/questions/65850978/how-to-exclude-regex-matches-from-inside-urls-with-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In modern Javascript you can use dynamic length assertion in Javascript so you may try:

var reg = new RegExp('(?<!https?://\S*)\b${searchQuery}[\s.,?!]', 'gi');

RegEx Demo

(?<!https?://\S*) is negative lookbehind that will fail a match if http:// or https:// followed by 0 or more non-whitespace characters is found before the match.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...