简体   繁体   English

正则表达式拒绝连续字符

[英]Regex Reject Consecutive Characters

I am still very new to Regex and basically what I need to do is create a rule that accepts numbers and letters but no consecutive characters are allowed to be entered. 我仍然是Regex的新手,基本上我需要做的是创建一个接受数字和字母但不允许输入连续字符的规则。

For example: abcd --> ok, abbcd --> bad 例如:abcd - > ok,abbcd - > bad

I have most of it to work but the part I cant figure out is exactly how do I prohibit consecutive characters? 我有大部分工作,但我无法弄清楚的部分是我如何禁止连续的字符?

My Code so far: 我的代码到目前为止:

/^[A-Za-z-0-9]{8,15}$/i
>>> r = /^((\w)(?!\2))+$/i
>>> r.exec('abbcd')
null
>>> r.exec('abcd')
[ 'abcd',
  'd',
  'd',
  index: 0,
  input: 'abcd' ]

The \\2 part is a back reference and matches whichever character was last matched by the group (\\w) . \\2部分是后引用,匹配组最后一个匹配的字符(\\w) So the negative lookahead (?!\\2) means "not followed by the character itself." 所以负面的前瞻(?!\\2)意味着“没有跟随角色本身。” If some terms I used here are unfamiliar to you, you should look them up on MDN's Regular Expression Documentation . 如果我在这里使用的某些术语对您来说不熟悉,您应该在MDN的正则表达式文档中查找它们。

To limit the length of the accepted strings to 8-15 characters as in the OP, change the + to {8,15} : 要将接受的字符串的长度限制为OP中的8-15个字符,请将+更改为{8,15}

>>> r = /^((\w)(?!\2)){8,15}$/i
>>> r.exec('abcd')
null
>>> r.exec('abcdabcd')
[ 'abcdabcd',
  'd',
  'd',
  index: 0,
  input: 'abcdabcd' ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM