Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesnt [\n$] work while (\n|$) does?

Tags:

regex

pcre

We have this string (without new line at the end):

The quick brown fox jumps over the lazy dog

I want to match the entire string until new line \n or end $ occurs.

  • I firstly tried: [\n$] - didnt work.
  • Then i tried (\n|$) - did work

Question: Why doesnt [\n$] match the string while (\n|$) does?

like image 367
Zaffy Avatar asked Aug 06 '26 17:08

Zaffy


2 Answers

Because $ in a character class is seen as a literal

like image 89
Casimir et Hippolyte Avatar answered Aug 08 '26 10:08

Casimir et Hippolyte


Another way to look at it: a character class matches exactly one character. The end-of-line matched by $ is an empty string. That's why and end-of-line cannot be matched by a character class.

(As a consequence, the only possible interpretation for $ is the literal.)

like image 25
Joni Avatar answered Aug 08 '26 09:08

Joni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!