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

JavaScript中匹配任意内容且长度≤200的正则表达式问题

Fixing Your Regex to Match Any Character (With Length Limit)

Got it, let’s sort out this regex problem for you. The issue with your current pattern [a-zA-Z0-9 .,']{0,200} is that it only explicitly allows a tiny subset of characters—letters, numbers, spaces, dots, commas, and single quotes. Any other special characters (like $, %, !, etc.) get excluded, which is why they aren’t matching.

Here are the solutions you need, depending on whether you want to include line breaks or not:

Option 1: Match Any Character Except Line Breaks (Most Common Use Case)

Use this regex to accept any character except newlines, with a length between 0 and 200:

^.{0,200}$

Breakdown:

  • ^ Anchors the match to the start of the input.
  • . Matches any single character except line break characters (\n, \r, etc.).
  • {0,200} Enforces the length limit (0 to 200 characters total).
  • $ Anchors the match to the end of the input, ensuring there’s no extra content beyond the 200-character limit.

Option 2: Match All Characters (Including Line Breaks)

If you need to allow multi-line input (like text with newlines), use one of these compatible patterns:

Cross-Environment Compatible (Works Everywhere)

^[\s\S]{0,200}$

[\s\S] is a reliable trick to match any character: \s matches whitespace (including line breaks) and \S matches non-whitespace, so together they cover every possible character.

Modern JavaScript (ES2018+)

If you’re working in an environment that supports the s (dotAll) modifier (most modern browsers and Node.js), you can simplify it to:

^.{0,200}$

Just add the s modifier when creating the regex:

const regex = /^.{0,200}$/s;

The s modifier makes . match line break characters too, so you don’t need the [\s\S] workaround.

Testing It Out

Both patterns will correctly match inputs like:

  • 123ababb
  • abbd$5%
  • !@#$%^&*()_+-=[]{}|;:,.<>? (as long as it’s ≤200 characters)

They’ll reject any input longer than 200 characters, which is exactly what you need.

内容的提问来源于stack exchange,提问作者Pranay kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 21:27:52