-1

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

3
  • 1
    Why is "0/2" no match? Nothing wrong with in from a mathmatical point of view. Is "0%" a match? Is "1.44%" a match? For your current requirements (omitting 0%) you could use ^[1-9][0-9]*(?:%|\/[1-9][0-9]*)$ Commented Feb 3 at 11:14
  • Are saying literally: "1/2" or "50%" sans " "? If so it's just /1\/2|50%/ Commented Feb 3 at 12:52
  • DuesserBaest, zer00ne, Thanks FY comments! 1.44% is not correct, because I need to push user to fill for instance 3/8, not 37.5%. 0/2 is correct math, but incorrect in my case. Commented Feb 4 at 7:13

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

from the "exactly" and ^ and $ used in the question, I'm guessing that lines like 1/2abc and abc50% should not match but your regex does not exclude them (you need extra parentheses around the | or duplicate ^...$ around each case)
@jhnc fair enough, also "exactly" of course stands and falls with the quality of the given examples. But in hindsight, I'm guessing our interpretation makes sense.
ie. you have ab|cd when you need a(b|c)d or abd|acd
@C3roe perfect solution, thanks a lot!
0

Assuming that the whitespace in your first "Matches" line is a typo, you could do:

^[1-9][0-9]*(%|/[1-9][0-9]*)$ 

It is not clear if 1/234, 345/6, 78900%, etc, should match. I've assumed that they should. Note that excluding the second example (two numbers separated by slash, where first number is not smaller than second) is a bit complicated with basic regex syntax.

1 Comment

I've just read @DuesserBaest's comment in full and noticed I've come up with effectively the same regex

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.