我正在尝试验证字符串是否仅包含以下内容
1. Numbers (0-9) are valid 2. Letters (A-Z, a-z) are valid 3. No leading spaces are allowed 4. No trailing spaces are allowed 5. A space can be entered in the field text (outside of leading or trailing spaces) 6. The following special characters are allowed: 1. Underscore (_) 2. Hyphen (-) 3. Comma (,) 4. Dot (.)
以下内容对我有用,除了空格
/^[A-Za-z0-9][A-Za-z0-9\_\.\-\,\s]*$/g
如何避免具有相同正则表达式模式的前导空格和尾随空格?
最佳答案
如果中间可以有连续的空格字符,您可以使用一个可选部分,其中第二个字符类重复 0+ 次,以相同的字符类结尾,不包括 \s
^[A-Za-z0-9](?:[A-Za-z0-9_.,\s-]*[A-Za-z0-9_.,-])?$
或者使用\w
来匹配单词字符:
^[A-Za-z0-9](?:[\w.,\s-]*[\w.,-])?$
请注意,\s
也可能匹配换行符。
关于regex - 避免字母数字字符串上的前导和尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61544656/