Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions (RegEx) - One String Variable length

Tags:

c#

.net

regex

My application receives one barcode where its length is variable. It could be 5, 9, 12 or 14. I'm trying to use something like this: \w{14}|\w{12}|\w{9}|\w{5}

That regular expression is not correct. Is there any regular expression for different lengths? or What is the right way to combine different regular expressions?

Note: The reason why I'm using regular expressions is a long story.

like image 503
user2521649 Avatar asked Jun 25 '13 20:06

user2521649


1 Answers

Is this what you are looking for?

\b(\w{14}|\w{12}|\w{9}|\w{5})\b

Regular expression image

It will match all the words within your string that are either 14, 12, 9, or 5 characters long. You can then check these matches. See a string that contains several matches and non-matches here: http://www.debuggex.com/r/V9T8nHp7ep6yuJow

If you are only hoping to check that the entire string is a single match, use this (to check that it both starts and ends with one of your options):

^(\w{14}|\w{12}|\w{9}|\w{5})$

Also, all the barcodes I've seen consist only of numbers, is this is the case for you as well... you should replace all the \w with \d which is the same as [0-9]

like image 88
Dallas Avatar answered Sep 20 '22 13:09

Dallas