Sana.91
Sana.91

Reputation: 2249

Regular expression that accepts digits, letters and hyphens

I want a regular expression that accepts all numbers, alphabets and only the hyphen (‐) from special characters.

I am trying this expression: ^\d+$/[-]/[a-z] but it does not work. I want to accept expressions like this one:

Emp-IN-0000001

Can someone help me with this?

Upvotes: 0

Views: 1229

Answers (3)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

If it's always this format (Emp-IN-0000001), then use this regexp:

^[a-zA-Z]+-[a-zA-Z][a-zA-Z]-[0-9]+$

or, if you have extended regexps:

^[a-zA-Z]+-[a-zA-Z]{2}-\d+$

when there are always seven digits, use this:

^[a-zA-Z]+-[a-zA-Z]{2}-\d{7}$

You can even say:

^Emp-IN-\d{7}$

if it's exactly "Emp-IN-" + digits.

Btw, this is not C# specific, you can use these regular expressions with any language, as long as they support regexps at all.

Upvotes: 4

Furqan Safdar
Furqan Safdar

Reputation: 16698

If you stickily wants to follow this format Emp-IN-0000001, then you might need to use this regular expression:

^[a-zA-Z]+-[a-zA-Z]+-\d+$

Upvotes: 2

Martin Ender
Martin Ender

Reputation: 44259

I don't really get what you tried with your regular expression, but it is actually as simple as this:

^[a-zA-Z\d-]+$

Or if you want to allow empty strings:

^[a-zA-Z\d-]*$

If you use the case-insensitive modifier with your regular expression, you can leave out either the a-z or A-Z from both variants.

I recommend you read up on some regex basics in this great tutorial.

Upvotes: 1

Related Questions