簡體   English   中英

正則表達式允許標點符號和單詞之間的空格

[英]Regular expression to allow punctuation marks and spaces between words

我想要一個防止空格的正則表達式,並且只允許帶有標點符號的字母和數字(西班牙語)。 下面的正則表達式效果很好,但它不允許標點符號。

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

例如,當使用這個正則表達式時,“Hola como estas”很好,但是“Hola,como estás?” 不匹配。

如何將其調整為標點符號?

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

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

查看證明

解釋

                         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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM