Can't specify the start of an input string using a multi-line regex pattern in JavaScript?

In JavaScript, a multi-line flag changes the value ^

and $

:

Treat leading and trailing characters (^ and $) as working on multiple lines (i.e. matching the start or end of each line (with \ n or \ r delimiters), not just the beginning or end of the entire input line)

Well, with these characters from the picture, are there any other ways to mark the beginning of the input line? How can I specify that I want my multiline pattern to match only at the beginning of the input line?

I know I can check the index of the match using the index

return value property exec

, but is there a way to avoid the regex engine looking for the entire string in the first place?

+3


source to share


2 answers


No, JavaScript does not support absolute bindings ( \A

, \Z

and \Z

) like most other options. But are you sure you need them? The beginning of a line is usually the only place where you should use the anchor. Each subsequent line is automatically "anchored" to the new line that precedes it.



I suggest that you unset the multiline flag and make sure you are consuming all newlines explicitly. I know this is vague; if you would like to provide a sample code and / or tell us what problem you are trying to solve, we could do better.

+1


source


No, it ^

is the only inline assertion that checks the start of input and as you said its behavior is changed by a flag multiline

.



You can put some unique string at the beginning of the line you're testing as well as at the beginning of your regex, but that's a bit of a hack. Normally, as you said, you would check the index of the match returned.

+2


source







All Articles