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

如何让GB VAT号码正则表达式同时支持带空格与无空格格式?

Solution for Supporting Both Spaced and Unspaced GB VAT Numbers

Got it, let's fix this regex to cover both spaced and unspaced GB VAT formats without breaking existing valid cases. Here's the breakdown and solution:

First, Let's Recap Valid Formats

You need to support two main GB VAT patterns:

  • Numeric variant: Either GB999999973 (no spaces) or GB999 9999 73 (spaces after the 3rd and 7th digits)
  • Alphanumeric variant: GBGD001 / GBHA599 (two uppercase letters + three digits, no spaces in this case)

The Updated Regex

This regex handles both spaced and unspaced versions seamlessly:

^GB(?:\d{3}(?:\s?)\d{4}(?:\s?)\d{2}|[A-Z]{2}\d{3})$

How It Works

Let's break down each component to make it clear:

  • ^GB: Ensures the string starts exactly with "GB" (no leading spaces or extra characters)
  • (?:...): A non-capturing group to wrap our two valid format options
    • Numeric case: \d{3}(?:\s?)\d{4}(?:\s?)\d{2}
      • \d{3}: Matches the first 3 digits
      • (?:\s?): Makes a single whitespace optional (works for both spaced and unspaced numeric VATs)
      • \d{4}: Matches the next 4 digits
      • (?:\s?): Another optional whitespace for the final segment
      • \d{2}: Matches the last 2 digits
    • Alphanumeric case: [A-Z]{2}\d{3}
      • [A-Z]{2}: Matches the two uppercase letters after GB
      • \d{3}: Matches the final three digits
  • $: Ensures the string ends right after the VAT number (no trailing spaces or extra characters)

Tested Valid Cases

This regex will correctly match all your examples:

  • Unspaced numeric: GB999999973
  • Spaced numeric: GB999 9999 73
  • Alphanumeric: GBGD001, GBHA599

It will also reject invalid formats like GB 999999973 (space after GB), GB9999 99973 (wrong space position), or GBG1234 (invalid alphanumeric structure).

内容的提问来源于stack exchange,提问作者Rafaël De Jongh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:17:24