$ in regex not parsed from end of line

I have a problem with the following regex:

var s = "http://www.google.com/dir/file\r\nhello" var re = new RegExp("http://([^/]+).*/([^/\r\n]+)$"); var arr = re.exec(s); alert(arr[2]); 

Above, I expect arr [2] (ie capture group 2) to be a β€œfile” that matches the last 4 characters in the first line after applying greedy. *, Rollback due to / to the pattern, and then snapping to the end of the line at $.

In fact, arr [] is null, which means the pattern didn't even match.

I can change this a bit so that it does exactly what I intend:

 var s = "http://www.google.com/dir/file\r\nhello" var re = new RegExp("http://([^/]+).*/([^/\r\n]+)[\r\n]*"); var arr = re.exec(s); alert(arr[2]); // "file", as expected 

My question is not as much as HOW to capture the "file" from the end of the first line in s. Instead, I try to understand why the first regular expression fails, and the second succeeds. Why does $ not match the line break \ r \ n in example 1? isn't that the only purpose of his existence? Is there anything else I am missing?

Also consider the same first regular expression that is used in sed (with extended regular expression mode with -r):

 $ echo -e "http://www.google.com/dir/file\r\nhello" |sed -r -e 's#http://([^/]+).*/([^/\r\n]+)$#\2.OUTSIDE.OF.CAPTURE.GROUP#' <<OUTPUT>> file.OUTSIDE.OF.CAPTURE.GROUP hello 

Here capture group 2 captures the β€œfile” and nothing else. "hello" appears on the output, but does not exist inside the capture group, as evidenced by the position of the line ".UUTSIDE.OF.CAPTURE.GROUP" on the output. So the regex works according to my understanding in sed, but does not use the built-in Javascript regexp engine.

If I replaced \ r \ n in the input line with only \ n, the behavior will be the same for all three of the above examples, so this should not be relevant as far as I can tell.

+5
source share
1 answer

You need to enable multi-line regex mode according to end-of-line characters

 var re = new RegExp("http://([^/]+).*/([^/\r\n]+)$", "m"); 

http://javascript.info/tutorial/ahchors-and-multiline-mode

enter image description here

+5
source

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


All Articles