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.

CodeMonkey
  • 2,265
  • 9
  • 48
  • 94

2 Answers2

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}|)$
Caio Oliveira
  • 1,243
  • 13
  • 22
  • 2
    +1 Did you read my mind? Was about to write exactly the same regex, incl. posting same demo link :-P – donfuxx Apr 15 '14 at 23:36
  • `Warning: An empty alternative effectively makes this group optional which suggests the alternative is completely redundant` The solution was posted by other question http://stackoverflow.com/questions/15723663/using-regex-to-filter-year-of-fixed-length-0-or-4-digit `^([0-9a-zA-Z]{4})?$` **DOWNVOTE!** – raiserle Apr 15 '14 at 23:42
  • Yes, thats what i want.. either an empty value or a value of 4 chars long. – CodeMonkey Apr 15 '14 at 23:43
  • Why would you prefer using `ˆ(expr|)$` over `ˆ(expr)?$` – nomæd Apr 19 '22 at 07:55
  • 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. – Caio Oliveira Apr 21 '22 at 11:02
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

Community
  • 1
  • 1
Fra
  • 4,918
  • 7
  • 33
  • 50