首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >允许在单词之间使用标点符号和空格的正则表达式

允许在单词之间使用标点符号和空格的正则表达式
EN

Stack Overflow用户
提问于 2020-08-29 03:42:52
回答 1查看 91关注 0票数 2

我想要一个正则表达式,防止空白,只允许字母和数字与标点符号(西班牙语)。下面的正则表达式运行得很好,但它不允许使用标点符号。

代码语言:javascript
复制
^[a-zA-Z0-9_]+( [a-zA-Z0-9_]+)*$

例如,使用正则表达式"Hola como estas“是可以的,但是"Hola,como estás?”不匹配。

如何将其调整为标点符号?

EN

回答 1

Stack Overflow用户

发布于 2020-08-29 03:45:47

使用\W+代替空格,并在末尾添加\W*

代码语言:javascript
复制
/^[a-zA-Z0-9_]+(?:\W+[a-zA-Z0-9_]+)*\W*$/

请参阅proof

说明

代码语言:javascript
复制
                         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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63640013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档