Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx (.*?) any thing but one character

Tags:

regex

php

pcre

I'm trying to match something with a pattern amongst the lines of /^(.*?)\/$. However, since (.*?) already matches / it also matches anything/////////// but I only want it to match anything/.

Is there a nice way to exclude / from (.*?) or alternative solutions?

like image 412
KaekeaSchmear Avatar asked Nov 28 '25 20:11

KaekeaSchmear


1 Answers

Use a negated character class [^\/]:

/^([^\/]*)\/$/

See the regex demo

In PHP, you may avoid overescaping in the pattern using some other delimiter, say ~:

$rx = '~^([^/]*)/$~';

Details:

  • ^ - start of string
  • ([^\/]*) - Group 1 capturing 0+ chars other than /
  • \/ - a literal /
  • $ - end of string.

Note you do not need a lazy quantifier *? with this negated character class since it will be much more efficient with a greedy one, *.

like image 128
Wiktor Stribiżew Avatar answered Dec 01 '25 10:12

Wiktor Stribiżew



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!