javascript - 正则表达式允许单词之间的标点符号和空格
问题描述
我想要一个正则表达式,它可以防止空格,只允许带有标点符号的字母和数字(西班牙语)。下面的正则表达式效果很好,但它不允许标点符号。
^[a-zA-Z0-9_]+( [a-zA-Z0-9_]+)*$
例如,当使用这个正则表达式“Hola como estas”时很好,但是“Hola, como estás?” 不匹配。
如何将其调整为标点符号?
解决方案
Use \W+
instead of space and add \W*
at the end:
/^[a-zA-Z0-9_]+(?:\W+[a-zA-Z0-9_]+)*\W*$/
See proof
EXPLANATION
EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
[a-zA-Z0-9_]+ any character of: 'a' to 'z', 'A' to 'Z',
'0' to '9', '_' (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
\W+ non-word characters (all but a-z, A-Z, 0-
9, _) (1 or more times (matching the
most amount possible))
--------------------------------------------------------------------------------
[a-zA-Z0-9_]+ any character of: 'a' to 'z', 'A' to
'Z', '0' to '9', '_' (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
)* end of grouping
--------------------------------------------------------------------------------
\W* non-word characters (all but a-z, A-Z, 0-
9, _) (0 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
推荐阅读
- tensorflow - 如何创建一个 Keras 层来进行 4D 卷积(Conv4D)?
- ios - Xcode 11.3.1 没有将二进制第三方框架嵌入到包 (IPA)
- ios - Firestore分页查询未返回所有结果
- asp.net - 如何在 TextMode="Date" 中首先插入“日”而不是月 - ASP.NET C#
- php - 如何在不知道键名的情况下回显关联数组的第一个键值
- java - 我的数组成员为空,即使它们已初始化
- javascript - JS 秒计数计时器通过单击按钮停止
- python - BigQuery GCP Python 集成
- typescript - 无法使用 Fetch TYPESCRIPT POST 多部分/表单数据
- kubernetes - CoreDNS 在获取端点、服务、命名空间时遇到问题