Regex - does not match group if it starts with string in javascript

I am struggling with some regex, in javascript, which does not have the typical lookbehind option, to match only the group if it is not preceded by a line:

(^|)(www\.[\S]+?(?= |[,;:!?]|\.( )|$)) 

therefore in the next

 hello http:/www.mytestwebsite.com is awesome 

I am trying to determine if the site has surpassed www.mytestwebsite.com

 / 

and if it’s not me, then I don’t want to correspond, otherwise I coincide. I tried to use a look ahead, but it looked contradictory with what I already had in mind.

I played with placement (?! & # X2f) in different areas without success.

 (^|)((?!&#x2f)www\.[\S]+?(?= |[,;:!?]|\.( )|$)) 

Look forward to not match if a match precedes

+5
source share
2 answers

Due to the lack of lookbehinds in JS, the only way to achieve your goal
matches those websites that contain erroneous / .

This is because viewing will not advance the current position.
Position only on expendable text will promote the position.

But a good solution has always been to include erroneous text as an option
in regular expression. You put some capture groups around him and then tested the groups for the match. If it matches, skip to the next match.

This requires sitting in a while loop checking for every successful match.
In the regex below, if matches group 1, don't save the URL of group 2,
If not, save the group 2 URL.

(/)?(www\.\S+?(?= |[,;:!?]|\.( )|$))

Formatted by:

  ( &\#x2f; )? # (1) ( # (2 start) www\. \S+? (?= &\#x20; | [,;:!?] | \. ( &\#x20; ) # (3) | $ ) ) # (2 end) 
+3
source

Another option (and I performed zero performance testing) would be to use string.replace() with a regex and a callback as the second parameter.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Then, inside the replace function, add / add invalid / characters that you do not want to match with the matching string using the offset parameter passed to the callback (see docs above), you can determine each match and its position and determine whether to replace the text or no.

0
source

Source: https://habr.com/ru/post/1237437/


All Articles