简体   繁体   中英

In a RegEx I need to allow spaces only in middle and prevent spaces at beginning and end

I have a requirement wherein I have below requiements to validate a name field:

  1. don't allow following symbols: &(¥)*/+}{¿?¡_^ ~¨¬;:@!"#&\\|-'
  2. can´t contain numbers
  3. can´t contain blank spaces at the begining or at the end

I have used below regex:

^[^\\s0-9&(¥)*/+}\\\\{¿?¡_^~¨¬;:@!#&\"|-]*$

It is fulfilling all the conditions except that is is also restricting spaces in between the string. For ex:

It restricts format: "firstname lastname"

I need the above format to be allowed. I only need to restrict spaces at beginning and end.

I assume it is used in some kind of a RegularExpressionAttribute validation, and you just want to use a single pattern for this.

You have already the first building block:

[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]

This matches any char but the ones defined in the set. It does not match whitespace. If you quantify with * and wrap with anchors, no whitespace will be allowed anywhere in the string. So, you just need to add an optional group (quantified with * or ? or {x,y} depending on how many spaces you want to allow):

^[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+(?:\s[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+)*$
                                        ^^^                                         ^^

If you want to also match an empty string, wrap the pattern with an optional non-capturing group:

^(?:[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+(?:\s[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+)*)?$
 ^^^                                                                                     ^^

Escape backslashes as needed.

As for the hyphen in the names: it might be appropriate to allow it in the same place as whitespace:

^(?:[^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+(?:[\s-][^\s0-9&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+)*)?$
                                              ^^^^^

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