Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allow only numbers AND may 'contain' slash AND must not start or end with slash

Tags:

regex

what I have is this:

[^\/][\d]*[^\/]

The problem I still have is: slash at the beginning is still allowed

Anyone an idea?

Thanks in advance

like image 216
ThinkTeamwork Avatar asked Oct 16 '25 10:10

ThinkTeamwork


1 Answers

The [^/] matches any char, not just a digit. Besides, to validate a whole string, you need to use anchors, or a method that anchors the match at start and end of the string.

You may use

^(?!\/)[\d\/]*$(?<!\/)

Or

^\d(?:[\/\d]*\d)?$

See the regex demo #1 and regex demo #2.

Regex #1 details

  • ^ - start of string
  • (?!\/) - no / allowed at the start
  • [\d\/]* - 0 or more digits or slashes
  • $- end of string
  • (?<!\/) - fail the match if there is a / at the end.

Regex #2 details

  • ^ - start of string
  • \d - a digit
  • (?:[\/\d]*\d)? - an optional non-capturing group matching 0 or more / or digit chars and then a digit
  • $ - end of string.
like image 143
Wiktor Stribiżew Avatar answered Oct 19 '25 09:10

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!