Zulhafiz Marliza
Zulhafiz Marliza

Reputation: 29

Regular expression string only with limit

I'm learning to create regex queries on string with a limit of 30 characters (mainly use for First name and Last Name)

I'm using asp.net C# but I don't seem to find it correct with the codes I'm writing

[WebMethod]   
public bool stringOnlyAndLimit(String strToCheck) 
{
    Regex stringonly = new Regex("[^a-zA-Z]{1,30}"); 
    return !stringonly.IsMatch(strToCheck);
}

Thanks in advance

Upvotes: 1

Views: 1284

Answers (5)

JNYRanger
JNYRanger

Reputation: 7097

Your regular expression [^a-zA-Z]{1,30} currently says give me anything that is NOT the letters a-z & A-Z because of the carrot ^ within the brackets. Remove this and it will work for a single string with no white space.

If you want to check for first and last name with one RegEx including the space character and be under 30 characters it should be something like this:

^[a-zA-Z\s]{1,30}$

Upvotes: 1

Habib
Habib

Reputation: 223422

If you want to learn RegEx then ignore this answer, otherwise

A Non-RegEx option. You don't need Regex for something like that, you can do:

public bool stringOnlyAndLimit(String strToCheck)
{
 return strToCheck.Length < 31 && strToCheck.All(r => char.IsLetter(r));        
 //return strToCheck.Length < 31 && !strToCheck.Any(r => char.IsDigit(r));
}

With RegEX

public static bool stringOnlyAndLimit(String strToCheck)
{
    Regex stringonly = new Regex("^[a-zA-Z ]{1,30}$");
    return stringonly.IsMatch(strToCheck);
}

Upvotes: 2

Bibhu
Bibhu

Reputation: 4091

Try this regular expression

^[A-Za-z]{0,30}$

Upvotes: 0

Click2Death
Click2Death

Reputation: 786

Not particularly for C#, ^ is a NOT sign inside brackets. So [^abc] will match any character except a, b, or c.

So your regex should be [a-zA-Z]{1,30}

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

You can try something like this:-

^[a-zA-Z ]{1,30}$

Upvotes: 1

Related Questions