Javascript 正则表达式-无顺序空间
我正试图通过正则表达式实现这些任务:Javascript 正则表达式-无顺序空间,javascript,regex,Javascript,Regex,我正试图通过正则表达式实现这些任务: 字符串必须以字母开头 字符串的最大长度为30个字符 字符串可以包含数字、字母和空格() 字符串可能不区分大小写 字符串不应按顺序包含多个空格 字符串不能以空格结尾 在浏览了RegEx wiki和其他RegEx问题之后,我得到了以下表达式: /^([A-Z])([A-Z0-9]){0,29}$/i 虽然这成功地完成了任务1-4,但我在任务5和6中找不到任何内容 注意:我对正则表达式使用Javascript 字符串不应按顺序包含多个空格 当匹配一个空间时,对另一
/^([A-Z])([A-Z0-9]){0,29}$/i
虽然这成功地完成了任务1-4,但我在任务5和6中找不到任何内容
注意:我对正则表达式使用Javascript
字符串不应按顺序包含多个空格
当匹配一个空间时,对另一个空间进行负前瞻
字符串不能以空格结尾
在匹配空格时,字符串结尾也要进行负前瞻:
/^([A-Z])([A-Z0-9]| (?! |$)){0,29}$/i
^^^^^^^^^
这个正则表达式与Ruby一起工作。我想Javascript也会这样
r = /^(?!.{31})\p{Alpha}(?:\p{Alnum}| (?! ))*(?<! )$/
"The days of wine and 007" =~ r #=> 0 (a match)
"The days of wine and roses and 007" =~ r #=> nil (too long)
"The days of wine and 007" =~ r #=> nil (two consecutive spaces)
"The days of wine and 007!" =~ r #=> nil ('!' illegal)
请注意,空间是从自由间距模式中定义的正则表达式中剥离出来的,因此必须保护要保留的空间。我将每个字符都放在一个字符类中(
[]
),但是\s
也可以使用(尽管它匹配空格、制表符、换行符和其他一些字符,这应该不会有问题)。哇!太近了,但太远了。谢谢你的帮助,伙计!这是一个相当慢的方法。
/
^ # beginning of string anchor
(?!.{31}) # 31 characters do not follow (neg lookahead)
\p{Alpha} # match a letter at beg of string
(?: # begin a non-capture group
\p{Alnum} # match an alphanumeric character
| # or
[ ] # match a space
(?![ ]) # a space does not follow (neg lookahead)
)* # end non-capture group and execute >= 0 times
(?<![ ]) # a space cannot precede end of string (neg lookbehind)
$ # end of string anchor
/x # free-spacing regex definition mode