Click here to Skip to main content
15,031,132 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I have a specific requirement where a string should be verified whether it contains only the below:
1. Alphabets (smaller and upper cases)
2. Numbers
3. Dot .
4. Underscore _

The string can have any combination of the above 4 but not other than these.


Thanks & Regards,
Mathi
Posted

Try this:
^[\d\._\w]+$

also read: The 30 Minute Regex Tutorial[^]
   
Comments
Mathi2code 21-Jan-15 6:48am
   
I tried using this but got unrecognised escape sequence as build error. If I remove that escape sequence it didnt work as expected.
Peter Leow 21-Jan-15 6:52am
   
put it into string literal for use in c# programs like this:
@"^[\d\._\w]+$"
test it here: http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
Mathi2code 21-Jan-15 8:42am
   
this worked thanks
This is one expression that should do the trick
^[a-zA-Z1-9_\.]+$


a-zA-Z Will get lower and upper case English characters
1-9 Will get numbers
\. Will get the dot
_ Will get the underscore

There are many other ways to do this.
Have a look at Regular Expressions Info/[^]
   
Comments
Mathi2code 21-Jan-15 6:46am
   
I think the escape sequence is not required for dot.
George Jonsson 21-Jan-15 7:14am
   
It is. A dot without escape sequence will grab any character.
"The dot matches a single character, without caring what that character is. The only exception are line break characters. In all regex flavors discussed in this tutorial, the dot does not match line breaks by default."
See http://www.regular-expressions.info/dot.html[^]
jaket-cp 21-Jan-15 7:32am
   
0-9 :)
agreed on the dot escape
I assume you mean ASCII letters only. In that case, this should do the trick:

C#
Regex regex = new Regex("^[0-9a-zA-Z._]+$");

if(regex.IsMatch(stringToTest))
{
    // string is OK.
}
else
{
    // string is not OK.
}
   
Comments
George Jonsson 21-Jan-15 7:16am
   
The dot (.) should be escaped.
Staffan Bruun 21-Jan-15 7:25am
   
Not when it is part of a character class.
C#
Regex checkString = new Regex("^[0-9a-zA-Z._]+$");


Even this works with ^ in the start and + with the $

Thanks & Regards,
Mathi.
   
Comments
George Jonsson 21-Jan-15 7:21am
   
The dot (.) should be escaped
C#
Regex checkString = new Regex("[0-9a-zA-Z._]$");
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900