如何编写匹配10-50间可选带-1/2数值的正则表达式?
Regex for Validating 10-50 (Inclusive) with Optional "-1/2" Suffix
Alright, let's build exactly what you need for your text box validation. First, let's lock in the requirements to make sure we cover every case: we need to match integers from 10 up to 50 (including 50), and allow an optional "-1/2" suffix—so both pure integers like 50 and values like 49-1/2 should pass without issue.
Final Regex
^(1[0-9]|[2-4][0-9]|50)(-1/2)?$
Let's Break It Down
Every part of this regex serves a specific purpose, so you know exactly why it works:
^and$: These anchors ensure we match the entire input string—no extra spaces, leading/trailing characters, or partial matches slip through. Critical for text box validation where you don't want invalid input sneaking in!1[0-9]: Catches all numbers from 10 to 19 (starts with a 1, followed by any digit 0-9)[2-4][0-9]: Covers every integer from 20 to 49 (starts with 2, 3, or 4, followed by any digit 0-9)50: Explicitly matches the upper limit (since 50 doesn't fit the previous patterns, we call it out directly to avoid gaps)(-1/2)?: The?makes this group optional—so the "-1/2" suffix can appear 0 or 1 times. Perfect for allowing both pure integers and the suffixed version you need.
Test Cases to Verify
Should Match:
10(minimum valid integer)27(mid-range integer)49(just below the 50 limit)50(maximum valid integer)12-1/2(valid integer with the allowed suffix)50-1/2(max integer with the suffix)
Should NOT Match:
9(too low, below the 10 minimum)51(too high, above the 50 limit)10-1/3(wrong suffix—only "-1/2" is permitted)30.5(decimal instead of the required suffix format)15(leading space, caught by the^anchor)25-(partial, incomplete suffix)
内容的提问来源于stack exchange,提问作者kali linux
相关产品推荐
相关产品推荐

