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

如何修复正则表达式:移除下划线与&,仅允许指定合法字符

Fixing Your Regex to Match Only Allowed Characters

Let's break down what's wrong with your current regex and fix it properly:

Issues with the Original Regex: ^[\.\w?\-' ]+$

  1. \w includes underscores: The shorthand \w matches a-zA-Z0-9_—the underscore is the unwanted character here that's slipping through.
  2. HTML entity confusion: ' is an HTML-escaped way to write a single quote, but in a regex pattern, this gets interpreted as literal characters: &, a, m, p, ;, a, p, o, s, ;. That's why & is being incorrectly allowed.

The Corrected Regex

Use this pattern instead, which explicitly defines only the characters you want to allow:

^[a-zA-Z0-9' ?-.]+$

Breakdown of the Fixed Regex:

  • a-zA-Z0-9: Matches all uppercase/lowercase letters and digits (no underscores, since we're avoiding \w).
  • ': Directly includes the single quote (no need for HTML entities here—just write the literal character, making sure your string escaping handles it correctly if needed).
  • : Allows spaces.
  • ?: Allows question marks (no escaping needed inside the character set).
  • -: Placed at the end of the character set to avoid being interpreted as a range operator (like a-z). If you put it elsewhere, you'd need to escape it with \-, but putting it last is cleaner.
  • .: Matches literal periods (no escaping needed inside the character set).
  • +: Ensures there's at least one allowed character (adjust to * if empty strings should be allowed).
  • ^ and $: Anchor the regex to match the entire string, not just a substring.

Testing Examples

  • ✅ Should match: Hello World? This is a test-123. 'Valid string'
  • ❌ Should NOT match: Hello_World (contains underscore), Hello&World (contains &), Invalid! (contains exclamation mark)

内容的提问来源于stack exchange,提问作者ShaQ.Blogs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:26:05