1

In my application edittext value need at least one digit and one alphabet is mandatory, and some special characters are optional i.e ".-", 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

rams
  • 1,558
  • 7
  • 25
  • 48

1 Answers1

2

You could use a positive lookahead (?= to assert at least one occurrence of a-z 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 fourth bird
  • 154,723
  • 16
  • 55
  • 70