正则表达式,允许标点符号和单词之间的空格

问题描述

我想要一个防止空格的正则表达式,并且只允许带标点符号的字母和数字(西班牙语)。下面的正则表达式效果很好,但是不允许使用标点符号

^[a-zA-Z0-9_]+( [a-zA-Z0-9_]+)*$

例如,当使用此正则表达式时,“ Hola como estas”很好,但是“ Hola,comoestás?”不匹配。

如何调整标点符号

解决方法

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

/^[a-zA-Z0-9_]+(?:\W+[a-zA-Z0-9_]+)*\W*$/

请参见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','_' (1 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
  )*                       end of grouping
--------------------------------------------------------------------------------
  \W*                      non-word characters (all but a-z,0-
                           9,_) (0 or more times (matching the most
                           amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n,and the end of the
                           string