You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写匹配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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:57:22