Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for Empty String or 10 digits

Tags:

c#

regex

To start: I've just started with Regexes, and I've had a really difficult time understanding what's going on with them. Just a heads-up.

For a project, I'm trying to develop a regex that takes either A) an empty string (in C# speak, ""), or B) ten (10) digits. I've been able to figure out how to accomplish the 10-digits part:

"^[0-9X]{10}$"

...But not the 'empty string or' part. which I imagine would be something like:

"^[]$|^[0-9X]{10}$"

Obviously that doesn't work, but I have no idea how to write something that does, even though there are quite a few topics on the matter.

Questions:

A) What is a regex that will return true if the given string is either a string.Empty (rather, ""), or exactly 10 digits?

B) Please explain how exactly it works. It's not that I haven't been trying to learn (I did figure out that the ^$ are anchors for exact-string matching, and that | is the OR operator...), it's just that regexes apparently do not come naturally to me...yet, I'm in a situation I must use them.

like image 431
Andrew Gray Avatar asked Jan 22 '13 17:01

Andrew Gray


People also ask

Which regex matches one or more digits?

+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

Is the empty string a regular expression?

ε, the empty string, is a regular expression.

What does an empty regex match?

An empty regular expression matches everything.

Can regex be used for numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.


2 Answers

(^$)|(^\d{10}$)

The first option matches the empty string, the second option matches 10 digits.

I don't know what your X is for, unless you're looking for a hex string, if that is the case, you'll want to do the following:

(^$)|(^[0-9a-fA-FxX]{10}$)
like image 106
Wes Cumberland Avatar answered Sep 28 '22 02:09

Wes Cumberland


^$|^[0-9X]{10}$

^ means match the start, $ means match the end as there is nothing in between, match nothing. If there is something, this doesn't match

| is the alternation operator, between alternatives

like image 38
Vorsprung Avatar answered Sep 28 '22 02:09

Vorsprung