修改Oracle正则表达式:仅允许域名前缀含2个及以上字符
Hey there! Let's tackle this regex issue you're facing. Your current pattern is letting through emails like a@b.com because it allows single-character domain labels (that's the b before the .com). We need to adjust things so only labels with 2 or more total characters are allowed—whether they're plain alphanumeric (like bb) or hyphenated (like b-domain).
Updated Regex
Here's the revised pattern that meets your requirements:
@((?:[A-Z0-9]{2,}|[A-Z0-9]+-[A-Z0-9]+)(?:-[A-Z0-9]+)*\.){1,8}[A-Z]{2,63}$
What Changed & Why
Let's break down the key adjustment:
- The original part
[A-Z0-9]+(which matched 1+ alphanumeric characters) was replaced with(?:[A-Z0-9]{2,}|[A-Z0-9]+-[A-Z0-9]+). This does two things:[A-Z0-9]{2,}: Ensures plain alphanumeric labels have at least 2 characters (sobbpasses,bfails).[A-Z0-9]+-[A-Z0-9]+: Allows hyphenated labels, but only if there's at least one character before and after the hyphen (sob-domainpasses, while invalid labels likeb-or-domainget blocked—though those aren't valid domain labels anyway).
- The rest of the pattern (
(?:-[A-Z0-9]+)*\.){1,8}[A-Z]{2,63}$) stays intact to support multiple hyphens in labels and valid top-level domain (TLD) lengths.
Testing Your Examples
Let's verify against your test cases:
a@b.com: Invalid → The labelbis only 1 character, which doesn't meet the minimum requirement.a@bb.com: Valid → The labelbbhas 2 alphanumeric characters, which checks out.a@b-domain.com: Valid → The hyphenated labelb-domainhas characters both before and after the hyphen, totaling more than 2 characters.
If you need to enforce this minimum length for all domain labels (not just the first one after @), this pattern works for that too—any subdomain label (like sub in a@sub.bb.com) will also need to meet the 2-character minimum.
内容的提问来源于stack exchange,提问作者user11311005

