Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have a string which may contain numbers.I want to write function which searches for substring which contains numbers.

I am not able to search for numbers in string

Please provide me with any ideas which will help.
Posted
Updated 19-May-11 0:44am
v3
Comments
Rojeh 19-May-11 8:04am    
what do you want to return??
the index of the substring(that contains numbers) in the string or a true\false value that tell you if the string contains the substring you are searching for??

Try this bade boy of a regex string: \b(?=[-/\\\\A-Za-z]*[0-9])(?=[-/\\\\0-9]*[A-Za-z])[A-Za-z0-9]+(?:[-/\\\\][A-Za-z0-9]+)*\b

It will find only strings that contains numbers.

string like this "Dam It12 is not45 that g00d".

Will give you:

"It12"
"not45"
"g00d"

Example
C#
System.Text.RegularExpressions.MatchCollection ms = System.Text.RegularExpressions.Regex.Matches("Dam It12 is not45 that g00d", @"\b(?=[-/\\\\A-Za-z]*[0-9])(?=[-/\\\\0-9]*[A-Za-z])[A-Za-z0-9]+(?:[-/\\\\][A-Za-z0-9]+)*\b");

foreach (System.Text.RegularExpressions.Match m in ms)
{
  Console.WriteLine(m.ToString());
}
 
Share this answer
 
v2
Comments
bsb25 19-May-11 7:19am    
its not working :(
Kim Togo 19-May-11 7:27am    
See updated answer, with code example.
Kim Togo 19-May-11 9:11am    
You got it working?
bsb25 19-May-11 11:03am    
yes Bro.Thanks for the help.5.
C#
  string abc = "deepthi12 "
char[] SpecialChars = "0123456789";.ToCharArray();
int indexOf = abc.IndexOfAny(SpecialChars);
if (indexOf != -1)
{
    //there should a number in the string
}
else
{
    //No number
}
 
Share this answer
 
Comments
bsb25 19-May-11 11:04am    
5 frm my side.
You can use Regex.Replace() to do this.
e.g. Regex.Replace(myString, @"\d", string.empty);
 
Share this answer
 
Comments
bsb25 19-May-11 6:32am    
i had changed the question.I want to search for it,not replace it.
try this also

string Result= StripNumbers("Fgadda734ddsg&^%^3284")
public string StripNumbers(string input)
        {
            Regex regEx = new Regex("[0-9]+");
            StringBuilder sb = new StringBuilder();
            foreach (char a in input)
            {
                if (!regEx.IsMatch(a.ToString()))
                {
                    sb.Append(a);
                }
            }

            return sb.ToString();
        }
 
Share this answer
 
Comments
bsb25 19-May-11 7:20am    
not working :(
string searchWithinThis = "ABCDEF1GHIJKs12343LMNOP";
string searchForThis = "DEF1";
int firstCharacter = searchWithinThis.IndexOf(searchForThis);
Console.WriteLine("First occurrence: {0}", firstCharacter);
 
Share this answer
 
v2

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