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

如何调整正则表达式以正确匹配0x开头的公钥格式?

Fixing Your Hex Public Key Regex

Got it, let's sort out this regex issue for you. The problem with your current pattern ^0x[a-fA-F0-9]{1,40} is that it doesn't anchor the end of the string. That means if someone enters a string that starts with 0x followed by 40+ hex characters (or even hex characters plus special symbols at the end), the regex will still match the valid prefix instead of rejecting the entire invalid input.

Here's the adjusted regex that meets your exact requirements:

^0x[a-fA-F0-9]{1,40}$

Let me break down what each part does to make it clear:

  • ^: Ensures the string starts right here—so nothing can come before the 0x
  • 0x: Literally matches these two characters, enforcing the required prefix
  • [a-fA-F0-9]: Matches any single hexadecimal character (supports both uppercase and lowercase letters)
  • {1,40}: Specifies that the hex character group can appear between 1 and 40 times (perfect for your "up to 40 characters" rule)
  • $: Anchors the end of the string—this ensures there are no extra characters (like special symbols, spaces, or extra hex digits) after the allowed 40 hex characters

Quick Test Cases

  • Your example public key 0xc1e5017fbc68aa3e56aa580708de9aa123d62d18 (0x + 40 hex chars): ✅ Matches
  • A shorter valid input like 0x123abc: ✅ Matches
  • An input with extra characters like 0x12345!: ❌ Rejects (the ! isn't a hex character)
  • An input with 41 hex chars: 0xabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz: ❌ Rejects (exceeds the 40-character limit)

If you actually need to enforce exactly 40 hex characters (like standard Ethereum addresses), just adjust the quantifier to {40} instead of {1,40}:

^0x[a-fA-F0-9]{40}$

内容的提问来源于stack exchange,提问作者e.k

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:20:35