如何编写正则匹配5至100间可选逗号分隔的整数?
Solution
To match a nullable comma-separated string where every integer is between 5 and 100 (inclusive), with no trailing commas, use this regex:
^(?:(?:5|6|7|8|9|[1-9]\d|100)(?:,(?:5|6|7|8|9|[1-9]\d|100))*)?$
Breakdown of the Regex
Let's break down each component to understand how it enforces your requirements:
^and$: Anchors to ensure we match the entire string from start to finish (no partial matches slip through).(?: ... )?: A non-capturing group wrapping the entire valid number sequence, marked optional with?to allow the empty string case.(?:5|6|7|8|9|[1-9]\d|100): Matches a single valid number in the range 5-100:5|6|7|8|9: Covers single-digit numbers from 5 to 9.[1-9]\d: Covers two-digit numbers from 10 to 99 (first digit 1-9, second digit 0-9).100: Explicitly matches the three-digit number 100.
(?:,(?:5|6|7|8|9|[1-9]\d|100))*: Matches zero or more additional valid numbers preceded by a comma. The*allows multiple entries, and non-capturing groups avoid unnecessary capture of subparts.
Verification Against Your Test Cases
Should Match Successfully:
"": The optional outer group is skipped, so it matches."12": Fits the two-digit number pattern[1-9]\d."5,100": 5 (single-digit) followed by a comma and 100 (exact match)."5,34,55,12": All numbers fall within 5-100, separated by commas with no trailing comma."5,8,15,9,94": All entries are valid numbers in sequence.
Should Match Fail:
"2": 2 isn't in the valid single-digit range (5-9), so no match."4,15": 4 is invalid, breaking the entire sequence."87, 3": 3 is invalid, plus the space after the comma isn't allowed (your original regex also rejects spaces; see the note below if you need to permit this)."39,7,23,62, 1": 1 is invalid, so the string doesn't match."25,": Trailing comma—there's no valid number after the comma, so the sequence doesn't fit the pattern.
Optional: Allowing Spaces Around Commas
If you need to permit optional spaces before/after commas (e.g., "5, 100" or "5 , 100"), modify the regex to include \s* around the comma:
^(?:(?:5|6|7|8|9|[1-9]\d|100)(?:\s*,\s*(?:5|6|7|8|9|[1-9]\d|100))*)?$
This adds \s* (zero or more whitespace characters) before and after each comma, making spaces optional.
内容的提问来源于stack exchange,提问作者Mutai Mwiti
相关产品推荐
相关产品推荐

