Regularly match a digit in a string

I will have a different string type (the string will not have a fixed format, they will be different every time) from them I want to remove a certain substring. How can a string be

OPTIDX 26FEB2009 NIFTY CE 2500
OPTIDX NIFTY 30 Jul 2009 4600.00 PE
OPTSTK ICICIBANK 30 Jul 2009 700.00 PA

      

I want to extract Rs (digit) from this string and store it in one variable and then there should be no Rs (digit) in that line.

What should a regex be for?

EDIT

private string ExtractingRupeesFromString(String str)
{
    Match match = Regex.Match(cellRecord, @"(\d+(?:\.\d+)?)\D*$");
    return match.Value.ToString();
}

for(int i=0;i<datagridview1.Rows.Count;i++)
{
    datagridview1["Rs",i].Value=ExtractingRupeesFromString(datagridview1["ScriptName",i].Value.ToString());
}

      

+2


a source to share


3 answers


If you don't want to extract only ['2500', '4600.00', '700.00'], you can use the following regex with the MULTILINE flag enabled

@"([+-]?\d+(?:\.\d+)?)\D*$"

      

Edit : Added additional [+ -] and some C # codes

string s = @"
OPTIDX 26FEB2009 NIFTY CE 2500
OPTIDX NIFTY 30 Jul 2009 4600.00 PE
OPTSTK ICICIBANK 30 Jul 2009 700.00 PA
";
Regex re = new Regex(@"([+-]?\d+(?:\.\d+)?)\D*$",RegexOptions.Multiline);
foreach (Match a in re.Matches(s)){
    System.Console.WriteLine(a.Groups[1]);
}

//2500
//4600.00
//700.00

      

Edit :



You can change

return match.Value.ToString();

      

to

return match.Groups[1].ToString();

      

to return only part of the number.

+2


a source


how

Match match = Regex.Match(str, @"[-+]?[0-9]*\.?[0-9]+");
Rupees=str.Substring(match.Index,match.Length);

      



Everything is good? Check your regular expression.

+1


a source


I agree with jack30lena. This can be done easily with a regular expression.

eg:

Regex blabla = new Regex(@"([^0-9]*(?<number>[0-9])+)*");
MatchCollection matches = blabla.matches("OPTIDX 26FEB2009 NIFTY CE 2500");
foreach(Match m in matches)
{
string number = m.Groups["number"].Value;
//do something with the match...
}

      

0


a source







All Articles