Ruby正则表达式咨询:匹配符合特定格式规则的字符串
Solution for Your Ruby Regex Requirements
Got it, let's fix that regex for you. The original pattern doesn't cover all your specific rules, so here's a tailored Ruby regex that meets every requirement you outlined:
/^(?!.*\s)(?!.*-.*_)(?!.*_.*-)(?=.*[A-Za-z])(?:[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*|[A-Za-z0-9]+(?:_[A-Za-z0-9]+)*)$/
Breakdown of the Regex
Let's walk through each part to explain how it enforces your rules:
^(?!.*\s): Negative lookahead to disallow any spaces anywhere in the string.(?!.*-.*_)(?!.*_.*-): Two negative lookaheads that ensure the string never contains both hyphens (-) and underscores (_) in any order.(?=.*[A-Za-z]): Positive lookahead to guarantee the string has at least one letter (uppercase or lowercase).- The main body uses a non-capturing group with two branches:
[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*: Handles strings with hyphens (no underscores). The pattern ensures hyphens are never at the start/end, and never consecutive—each hyphen must be surrounded by alphanumeric characters.[A-Za-z0-9]+(?:_[A-Za-z0-9]+)*: Handles strings with underscores (no hyphens). Same logic as above: underscores can't be at the start/end or consecutive.
$: Ensures the regex matches the entire string from start to finish.
Test Results
Valid Examples (Will Match)
a1_b_2_hello: Contains underscores (no hyphens), no leading/trailing underscores, no consecutive underscores, has letters.2b-ffg-er2: Contains hyphens (no underscores), no leading/trailing hyphens, no consecutive hyphens, has letters.abs: No special characters, has letters.123a: Ends with a letter, no special characters.
Invalid Examples (Will NOT Match)
_a1_b_2_hello: Starts with an underscore.2b-ffg_er2-: Contains both hyphen and underscore, plus ends with a hyphen.__: No letters, consists only of consecutive underscores.--: No letters, consists only of consecutive hyphens.a__: Consecutive underscores.b--2: Consecutive hyphens.
内容的提问来源于stack exchange,提问作者Andrey Deineko
相关产品推荐
相关产品推荐

