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

求匹配1-60数字的正则表达式,解决现有表达式误匹配问题

Fixing Your 1-60 Number Regex & Avoiding Partial Matches

Got it, let's tackle this regex issue head-on. Your current pattern [0-6][0-9] has two main problems: it matches invalid values like 00 (which falls outside your 1-60 range) and it doesn't anchor to the boundaries of the target—so it'll happily grab a valid substring from a longer number like 950 (hence the unwanted 50 match you're seeing).

Here's how to fix it, tailored to two common use cases:

Case 1: Match an entire input string (e.g., user enters a single number)

Use start (^) and end ($) anchors to ensure the entire string is a valid 1-60 number:

^(?:[1-9]|[1-5][0-9]|60)$

Breakdown of this pattern:

  • ^ = Marks the start of the string
  • (?:...) = A non-capturing group to group our valid number options without storing extra data
  • [1-9] = Matches single-digit numbers 1-9 (avoids 0)
  • [1-5][0-9] = Matches two-digit numbers 10-59
  • 60 = Explicitly matches the upper limit of your range
  • $ = Marks the end of the string

This will reject inputs like 950 entirely, and only accept numbers strictly between 1-60.

Case 2: Match standalone numbers within a larger text (e.g., "The limit is 50, not 950")

If you need to find valid 1-60 numbers embedded in text without matching parts of longer numbers, use word boundaries (\b) instead of start/end anchors:

\b(?:[1-9]|[1-5][0-9]|60)\b

The \b ensures the number is surrounded by non-word characters (spaces, punctuation, etc.) or the start/end of the text—so it won't pick out 50 from 950, but will match 50 when it's a standalone number.

Quick Test Cases to Verify

  • ✅ Valid matches: 1, 9, 10, 59, 60
  • ❌ Rejected values: 0, 61, 950, 00, 100

That should solve your partial match problem while strictly enforcing the 1-60 range!

内容的提问来源于stack exchange,提问作者Charles Truluck

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:42:58