How to make regex accept only one optional underscore?

I have below regex that accepts alphanumeric characters and few other language characters. Now I want to allow only one optional underscore (_) anywhere in the string. Can you please help on how to achieve it?

const serverUserRegex = /^[p{Ll}p{Lm}p{Lt}A-Za-z0-9u3000-u303fu3040-u309fu30a0-u30ffuff00-uff9fu4e00-u9fafu3400-u4dbfu3130-u318FuAC00-uD7AF]+$/ug

Answer

One straightforward way to enforce this would be to add the following negative lookahead assertion to the start of the pattern:

(?!.*_.*_)

This would reject any input having two (or more) underscores, which means that zero or one underscores would be acceptable. Your updated pattern:

const serverUserRegex = /^(?!.*_.*_)[_p{Ll}p{Lm}p{Lt}A-Za-z0-9u3000-u303fu3040-u309fu30a0-u30ffuff00-uff9fu4e00-u9fafu3400-u4dbfu3130-u318FuAC00-uD7AF]+$/ug
//                                   ^^ add underscore to your character class here

Leave a Reply

Your email address will not be published. Required fields are marked *