regex

Regex expression to match digits with slash or with percent: 1/2, 50%


What is a correct regex expression to match exactly "1/2" or "50%"?

Matches:

1/2 
1/10
10/23
13/30
50%
2%

No matches:

0/2
1/0
02/15
50
4
1/2%

I've tried /^([0-9]+/[0-9]+)|([0-9]+%)$/ but without success. I need to get exact matches


Solution

  • My attempt: ^(([1-9][0-9]*/[1-9][0-9]*)(?!%))|((?<!/)([1-9][0-9]*%))$ - https://regex101.com/r/rHvyKR/1

    If you don't want to allow for a single 0, then you can't use [0-9]+, you need to demand one character out of [1-9] first, and then [0-9]* optional after that. And I threw in a Negative Lookahead and a Negative Lookbehind, to exclude the edge cases.