简体   繁体   中英

Regex with numbers and alphabets mandatory, special characters optional

In my application edittext value need at least one digit and one alphabet is mandatory, and some special characters are optional ie ".- ", like any whare in the string. For example ram123- . or r_m-12.m or.--ram123 or ram123.-_. For this I need regex. I have already tried with this one

str_userId.matches("[A-Za-z0-9]*+[?.?_?-]")

But not working. Here how to add special characters are optional.

Thanks, In Advance

You could use a positive lookahead (?= to assert at least one occurrence of az and after that match at least a single digit [0-9] .

Before and after matching the digit, you could add the . _ and - to the character class [A-Za-z._-]* and repeat it 0+ times.

Note that a character class matches on of the listed characters. This notation [?.?_?-] , which could be written as [?._-] would also match a question mark instead of making the others optional

^(?=[^a-z\n]*[a-z])[A-Za-z._-]*[0-9][A-Za-z0-9._-]*$

Regex demo

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