Micks
Micks

Reputation: 3

C# Regular Expression to skip some special characters

I am newbie to Regex and trying to learn that. My requirement is to ONLY consider a string as valid if it has JUST small alphabets, absolutely nothing else. ex: abc, khj, sdfs are valid words but Abc, KHJ,123,a$bd are not valid.

I am writing a regular expression like this:

 private bool IsValid(string str)
 {
    Regex r = new Regex(@"[a-z][^<>%'=\$]");
    Console.WriteLine(str + " : " + r.IsMatch(str).ToString()); 
    return r.IsMatch(str);
 }

But when I pass on the following input to this method:

"a<>'b=b"
 "abc"
 "a$b"
"123"
"IHH"

it is identifying abc as valid but it is also recognizing a$b and a<>'b=b as valid words ! (returning true for those) I want to understand how to skip a$b and a<>'b=b ?? the method should return false for them.

Please help me understand.

Thanks

Upvotes: 0

Views: 1502

Answers (3)

Mitja Bonca
Mitja Bonca

Reputation: 4546

Use this kind of method with an appropriate pattern:

private bool IsValid(string str)
 {
    Regex r = new Regex(@"^[a-z]+$");
    Console.WriteLine(str + " : " + r.IsMatch(str).ToString()); 
    return r.IsMatch(str);
 }

Upvotes: 1

James
James

Reputation: 2841

Good Reference: RegEx Cheat Sheet

Try this: ^[a-z]+$

Upvotes: 0

test
test

Reputation: 1

Your regex will look like

var pat = /^[a-z]+$/;

Upvotes: 0

Related Questions