开发者

How to replace string of digits with a padded version of that string in regular expression substitution?

开发者 https://www.devze.com 2022-12-31 05:04 出处:网络
I\'ve got a string of digits that i开发者_开发百科s either 4 or 5 digits long and it needs to be padded with \"0\" till it\'s 6 digits long. Is this possible? I\'m using .Net framework.You don\'t need

I've got a string of digits that i开发者_开发百科s either 4 or 5 digits long and it needs to be padded with "0" till it's 6 digits long. Is this possible? I'm using .Net framework.


You don't need a regular expression to perform this operation. You can use string.PadLeft:

s = s.PadLeft(6, '0');

If you need to use regular expression (perhaps because you are performing some more complex replacement of which this is just a small part) then you can use a MatchEvaluator in combination with the above technique:

string s = "foo <12423> bar";
s = Regex.Replace(s, @"<(\d+)>", match => match.Groups[1].Value.PadLeft(6, '0'));

Result:

foo 012423 bar
0

精彩评论

暂无评论...
验证码 换一张
取 消