【问题标题】:regex to allow space and restrict special characters at the beginning of a non empty string正则表达式在非空字符串的开头允许空格并限制特殊字符
【发布时间】:2021-07-15 00:06:04
【问题描述】:

我想在 javascript 中创建一个 RegExp。如果字符串非空,则要求在字符串的开头允许空格。另外,我必须在字符串的开头限制一些特殊字符。

目前,我正在使用这个 RegExp -

 ^(?!^[=+-@]).*



these strings need to be passed from regexp test - 

foo
foo bar
       bar
       123bar
foo@bar.com



these string should fail - 
@foo
        @foo
'           ...spaces'
'' empty-string

请帮忙。

【问题讨论】:

  • 试试^(?! *[=+@-]|\s+$).*

标签: javascript regex


【解决方案1】:

你可以使用

^(?! *[=+@-]| +$).*

或者,匹配任何类型的空格:

^(?!\s*[=+@-]|\s+$).*

详情

  • ^ - 字符串开头
  • (?!\s*[=+@-]|\s+$) - 如果在当前位置右侧紧邻有
    • \s*[=+@-] - 零个或多个空格,然后是 =+@-
    • | - 或
    • \s+$ - 一个或多个空格直到字符串结束
  • .* - 尽可能多的零个或多个除换行符以外的字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多