Helping to make some easy regular exspression
I need reg exspression what make this "123.12312" -> "123.32", or "23.323" -> "23.32开发者_如何学Python" in c#. It must be only 2 digits after point :)
Assuming you are parsing a string and it has at least 2 digits after the point:
/[0-9]+\.[0-9]{2}/
I know you are asking about a Regex, but this seems like a better fit for Double.TryParse followed by proper formatting.
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/
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
}
精彩评论