2

I need to match a pattern where i can have an alphanumeric value of size 4 or an empty value. My current Regex

"[0-9a-z]{0|4}");

does not works for empty values.

I have tried the following two patterns but none of them works for me:

"(?:[0-9a-z]{4} )?");
"[0-9a-z]{0|4}");

I use http://xenon.stanford.edu/~xusch/regexp/ to validate my Regex but sometimes i get stuck for RegEx. Is there a way/tools that i can use to ensure i have to come here for very complex issues.

Examples i may want to match: we12, 3444, de1q, {empty} But not want to match : @$12, #12q, 1, qwe, qqqqq

No UpperCase is matching.

4
  • 1
    Can you show an example of what it is that you want to match? Commented Apr 15, 2014 at 23:32
  • Uppercase letters should be allowed? Commented Apr 15, 2014 at 23:33
  • @donfuxx no. but if i have to do i simply use A-Z/a-z|0-9 as set of chars ? Commented Apr 15, 2014 at 23:35
  • 2
    read this question stackoverflow.com/questions/15723663/… Commented Apr 15, 2014 at 23:35

2 Answers 2

7

Overall you could use the pattern expression|$, so it will try to match the expression or (|) the empty , and we make sure we don't have anything after that including the anchor $. Furthermore, we could enclose it with a capture group (...), so it will finally look like this:

ˆ(expresison|)$

So applying it to your need, it would end up to be like:

^([0-9a-z]{4}|)$

here is an example

EDIT:

If you want to match also uppercases, add A-Z to the pattern:

^([0-9a-zA-Z]{4}|)$
Sign up to request clarification or add additional context in comments.

5 Comments

+1 Did you read my mind? Was about to write exactly the same regex, incl. posting same demo link :-P
Warning: An empty alternative effectively makes this group optional which suggests the alternative is completely redundant The solution was posted by other question stackoverflow.com/questions/15723663/… ^([0-9a-zA-Z]{4})?$ DOWNVOTE!
Yes, thats what i want.. either an empty value or a value of 4 chars long.
Why would you prefer using ˆ(expr|)$ over ˆ(expr)?$
Just to be suggestive. In fact both are absolutely the same, and i've never found in any source it is a "bad practice" (or that it is slower and we should avoid using it). So to keep the same rational from the questioner, I opted using it this way.
0

I suppose "empty value" means empty line in the question above. If that's the case you can use this expression:

^\s*$|[a-z0-9]{4}

which will match alphanumeric patterns of size 4 or empty lines as explained here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.