gpt4 book ai didi

regex - 避免字母数字字符串上的前导和尾随空格

转载 作者:行者123 更新时间:2023-12-02 19:32:48 24 4
gpt4 key购买 nike

我正在尝试验证字符串是否仅包含以下内容

1.  Numbers (0-9) are valid2.  Letters (A-Z, a-z) are valid3.  No leading spaces are allowed4.  No trailing spaces are allowed5.  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_.,-])?$

Regex demo

或者使用\w来匹配单词字符:

^[A-Za-z0-9](?:[\w.,\s-]*[\w.,-])?$

请注意,\s 也可能匹配换行符。

关于regex - 避免字母数字字符串上的前导和尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61544656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com