Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex question ^[a-zA-Z0-9]{5,10}$

Tags:

java

regex

The above regular expression (in Java) matches a string of alpha numeric characters of length between 5 and 10.

How can I modify the above regular expression to match with the above requirements as well as matching with an empty string?

like image 254
siva636 Avatar asked Oct 26 '10 08:10

siva636


People also ask

What does regex a ZA Z0 9 mean?

The bracketed characters [a-zA-Z0-9] indicate that the characters being matched are all letters (regardless of case) and numbers. The * (asterisk) following the brackets indicates that the bracketed characters occur 0 or more times.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

How do I match a pattern in regex?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .

What is a ZA Z in regex?

Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.


2 Answers

Make it optional (match exactly one or zero times)

^([a-zA-Z0-9]{5,10})?$
like image 184
Jürgen Steinblock Avatar answered Sep 17 '22 16:09

Jürgen Steinblock


^(?:[a-zA-Z0-9]{5,10}|)$

like image 25
joni Avatar answered Sep 21 '22 16:09

joni