SRA
SRA

Reputation: 1691

How can I check the following conditions in c# using regular expression

I've a condition like this

if I enter the text format as

9 - This should only allow numbers
s- Should only allow special chars
a - should only allow alphabets
x - should allow alpha numerics

There may be combinations like, if I specify '9s' this should allow numbers and special chars, 'sa' - should allow alphabes and numerics etc..

How can I check these conditions using regular expressions using c#.

Thanks

Upvotes: 2

Views: 250

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336408

You can translate these conditions into regex like this:

  1. Start the regex with ^[.

  2. Then add one or more of the following:

    • Numbers: \p{N}

    • Special characters (i. e. non-alphanumerics): \W

    • Letters: \p{L}

    • Alphanumerics: \w

  3. End the regex with ]+$

  4. Enclose the regex in a verbatim string.

So, for "only letters", it's @"^[\p{L}]+$"; for "numbers and special characters", it's @"^[\p{N}\W]+$" etc.

Upvotes: 2

Pasan
Pasan

Reputation: 1

You cannot 'generate' regular expressions using C# unless you code for it. But you surely can go to a site like 'www.regexlib.com' to find and build the regular expressions you want.

Then you can execute your regular expressions using C# to validate user inputs. this link would give you the knowledge how to use C# for it.

Hope this helps, regards.

Upvotes: 0

Related Questions