简体   繁体   中英

Regex doesn't work for the last character

I have this Regex function:

^[a-zA-Z](?!.*[.'-]{2})[A-Za-z0-9 ]*(?:[.'-][A-Za-z0-9 ]*){0,2}$

And basically it's supposed to allow only letters/numbers and these special symbols: .'- inside of the word. It also detects if there are any consecutive special symbols and if there is >2 total of them used. For example:

.asd (WRONG)

aaaa (WRONG)

aaa (OK)

blabla. (WRONG)

bla.-bla (WRONG)

bla-bla (OK)

It also shouldn't allow special character to be in the front and back of the word. I've managed to do everything but not the special character at the end of the word. I don't know where to put $ for it to work. Do you have any suggestions? Maybe this formula can be simplified?

Thanks!

In the second half of your regex, where you match a special character, you should require that at least one "normal" character follows. So change the * in:

(?:[.'-][A-Za-z0-9 ]*)

...to a + :

(?:[.'-][A-Za-z0-9 ]+)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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