开发者

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜