最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex to match a pattern or empty value - Stack Overflow

programmeradmin1浏览0评论

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 / 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 e here for very plex 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.

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 e here for very plex 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.

Share Improve this question asked Apr 15, 2014 at 23:30 CodeMonkeyCodeMonkey 2,2959 gold badges50 silver badges97 bronze badges 4
  • 1 Can you show an example of what it is that you want to match? – sshashank124 Commented Apr 15, 2014 at 23:32
  • Uppercase letters should be allowed? – donfuxx 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 ? – CodeMonkey Commented Apr 15, 2014 at 23:35
  • 2 read this question stackoverflow./questions/15723663/… – raiserle Commented Apr 15, 2014 at 23:35
Add a ment  | 

2 Answers 2

Reset to default 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}|)$

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

发布评论

评论列表(0)

  1. 暂无评论