Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - No "p" at second position

Tags:

regex

I am learning Regex and after reading this post, I started doing some exercises and I got stuck on this exercise. Here are the two lists of words that should be matched and not matched

enter image description here

I started with

^(.).*\1$

and get bothered with sporous that get matched although it should not. So I found

^(.)(?!p).*\1$

that did the trick.

The best solution (uses one less character than my solution) given here is

^(.)[^p].*\1$

but I don't really understand this pattern. Actually I think I am confused about seeing the ^ anchor in a group [] and I am confused about seeing the ^ anchor somewhere else than at the beginning of the regex.

Can you help to understand what this regex is doing?

like image 218
Remi.b Avatar asked Nov 05 '25 23:11

Remi.b


2 Answers

Anything in square brackets is a character class. This context uses its own mini-syntax which simply lists the allowed characters [abc] or a range of allowed characters [a-z] or disallowed characters by adding a caret as the very first character in the character class [^a-z].

like image 162
tripleee Avatar answered Nov 07 '25 12:11

tripleee


Your solution uses a negative look-ahead (?!p) that does not consume characters, and just checks if the next character is not p.

The other solution uses a negated character class [^p] that will consume a character other than p.

So, the final solution depends on what you need to match/capture.

like image 43
Wiktor Stribiżew Avatar answered Nov 07 '25 14:11

Wiktor Stribiżew