PCRE Regex non-consecutive repeating

与世无争的帅哥 提交于 2019-12-24 01:55:13

问题


I'm trying to have a 6 character minimum, up to 15 chars total. First has to be alphanumeric (no special), next (up to) 13 to be alphanumeric and can include NON CONSECUTIVE (and only one of the following at a time) underscore OR period OR hyphen, then last character has to be alphanumeric.

example of okay: A_3.hj_3J

example not okay: F__3d66.K

example not okay: 6-_sd.6h9

This is what I have so far, I feel like it's close but annoyingly off. What am I doing wrong?

^[a-zA-Z0-9]{1}([_.-]?[a-zA-Z0-9])\S{4,13}[a-zA-Z0-9]{1}$

回答1:


There are couple of problems:

  1. Your regex pattern will also match an input of more than 15 characters.
  2. Your regex will also other non-allowed characters in the middle like @ or # due to use of \S

You can fix it by using a negative lookahead to disallow consecutive occurrence of period/hyphen/underscore and remove \S from middle of regex that allows any non-space character

^[a-zA-Z0-9](?!.*[_.-]{2})[\w.-]{4,13}[a-zA-Z0-9]$

RegEx Demo



来源:https://stackoverflow.com/questions/43418823/pcre-regex-non-consecutive-repeating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!