V
V
Vladimir2018-03-06 14:45:55
.NET
Vladimir, 2018-03-06 14:45:55

Why doesn't $ work in regular expression after lookahead?

Hello,
I can't figure out why $ doesn't work in the following situation.
There is a text

123_456
123_456789
, you need to extract 123 making sure that _456 is present and it's all on one line.
For this I use the following regular expression:
^123(?=_456)$

But it doesn't work with $. Why?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Saboteur, 2018-03-06
@Degot

lookahead is not a character set, it is an "anchor" that denotes a position.
So you end up with _456 and $ at the same position, so it doesn't work
Add the end of the line inside your lookahead
^123(?=_456$)

C
cicatrix, 2018-03-06
@cicatrix

Is your text single line or multiline?
Try it in different modes:
Regular expression options
Multiline (?m) Use multiline mode, where ^ and $ match the beginning and end of a line of text (not the beginning and end of the input line).
Singleline (?s) Use singleline mode, where a dot (.) matches any character (not every character except \n).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question