I've found that \A
can be emulated with:
(?<!\s)^
and PCRE(2)/re2 \z
(Python \Z
) can be emulated with:
$(?!\s)
How else can \A
and/or \z
be emulated in JS?
Even regular-expression.info has no mention of what I've presented.
I've found that \A
can be emulated with:
(?<!\s)^
and PCRE(2)/re2 \z
(Python \Z
) can be emulated with:
$(?!\s)
How else can \A
and/or \z
be emulated in JS?
Even regular-expression.info has no mention of what I've presented.
Apart from the lookarounds that you have used, you can try one of the following:
Disable the multiline modifier. InJavascript, by default, ^
matches \A
and $
matches \z
and use:
^|$
or
you can capture them in groups as shown below:
(^)[\s\S]*($)
(^)
- match the start of the first line and capture it in group 1[\s\S]*
- greedily match 0+ occurences of any character(including newlines)($)
- match the end of the last line and capture it in group 2When you have no need of ^
and $
as line-boundaries, then these symbols act like \A
and \z
by default. Demo:
let results =
`a good test with
a second line, and ending with a bad z
a third line, and a bad z
a final line, and a good z`
.match(/^a (\w+)|(\w+) z$/g);
console.log(results);
If you do need to use line-boundary detection in your regex, then you would normally use the /m
modifier, and then you can use your idea of look-around.
Alternatively, you could leave out the /m
modifier, and just use ^
and $
for \A
and \z
, but then use look-around for detecting the line boundaries:
(?<![^\n\r])
(?![^\n\r])
let results =
`a bad test with
a good line, and ending with a good z
a third line, after a good line, and a bad z
a final line, and a bad z`
.match(/(?<![^\n\r]). good|good .(?![^\n\r])/g);
console.log(results);
For specific cases you can sometimes use other techniques. For instance, by default (so without /s
) the pattern .*
will capture anything until the end of the line, so you can be sure to be at a line-end after that capture.