[英]Regular expression to allow punctuation marks and spaces between words
I want a regular expression that prevents white spaces and only allows letters and numbers with punctuation marks(Spanish).我想要一个防止空格的正则表达式,并且只允许带有标点符号的字母和数字(西班牙语)。 The regex below works great, but it doesn't allow punctuation marks.
下面的正则表达式效果很好,但它不允许标点符号。
^[a-zA-Z0-9_]+( [a-zA-Z0-9_]+)*$
For example, when using this regular expression "Hola como estas" is fine, but "Hola, como estás?"例如,当使用这个正则表达式时,“Hola como estas”很好,但是“Hola,como estás?” does not match.
不匹配。
How can I tweak it to punctuation marks?如何将其调整为标点符号?
Use \\W+
instead of space and add \\W*
at the end:使用
\\W+
代替空格并在末尾添加\\W*
:
/^[a-zA-Z0-9_]+(?:\W+[a-zA-Z0-9_]+)*\W*$/
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.