[英]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: 我有一项要求,其中有以下要求来验证名称字段:
&(¥)*/+}{¿?¡_^
~¨¬;:@!"#&\\|-' &(¥)*/+}{¿?¡_^
〜¨¬;:@!“#&\\ |-' 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. 我假设它用于某种RegularExpressionAttribute验证中,并且您只想为此使用单个模式。
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): 因此,您只需要添加一个可选组(用
*
或?
或{x,y}
量化,具体取决于要允许的空格数):
^[^\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&(¥)*/+}\\{¿?¡_^`~¨¬;:@!#&\"|-]+)*)?$
^^^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.