简体   繁体   中英

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?" does not match.

How can I tweak it to punctuation marks?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM