tags:

views:

79

answers:

4

Hi. I need reg exspression what make this "123.12312" -> "123.32", or "23.323" -> "23.32" in c#. It must be only 2 digits after point :)

+2  A: 

Assuming you are parsing a string and it has at least 2 digits after the point:

/[0-9]+\.[0-9]{2}/
Full Decent
A: 

I know you are asking about a Regex, but this seems like a better fit for Double.TryParse followed by proper formatting.

driis
A: 

Is there a particular reason you need to use Regular Expressions? I would think it'd be better to do something like String.Format("{0:0.00}", double). You can find a list of some helpful formatting examples at http://www.csharp-examples.net/string-format-double/

Timothy
It is good too. If My question was without worlds reg expression I would choose you answer.
Sergii
But in my code I will use your variant :).
Sergii
A: 

I don't realy know how regex works in C# but this is my regex

([0-9]+)(?:\.([0-9]{1,2})|)[0-9]*

Group 1 will get the part before the point and group 2 (if exists) will give the part behind the point (2 digits long)

the code here will produce all the matches out of a string:

StringCollection resultList = new StringCollection();
try {
    Regex regexObj = new Regex(@"([0-9]+)(?:\.([0-9]{1,2})|)[0-9]*", RegexOptions.Singleline);
    Match matchResult = regexObj.Match(subjectString);
    while (matchResult.Success) {
        resultList.Add(matchResult.Value);
        matchResult = matchResult.NextMatch();
    } 
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}
Spidfire
thank you too:).
Sergii