Regular expression help - sum the numbers in a string?
Not sure if this is the best approach but I have some string which represents the orientation of some blocks. For example '3V6V' means a row of 3 vertical blocks, and a row of 6 vertical blocks. '3V6V6V' means row of 3, 6, 6 all vertical. '4H4H4H4H' would be 4 rows of 4 horizontal blocks. i.e. every 2 characters constitutes a row. Each item will either have just horizontals or just verticals, no mix and match. What I need to do here is add the total of the digits to determine 开发者_Python百科the total number of blocks. How can I do that? I was thinking do some kind of string.split() and then if an array item is a number, add it to a running total. Is there a better approach to this? '4H4H4H4H' would be 16 and '3V6V6V' would be 15. Can someone point me in the right direction? There must be a fairly easy way to do this.
Thanks,
~ck in San Diegoint sum = Regex.Split(input, "[HV]")
.Where(s => !string.IsNullOrEmpty(s))
.Select(s => int.Parse(s))
.Sum();
Note that this will accept malformed input like "3H3" or "3H6V"
EDIT: In fact you can simplify this with String.Split:
int sum = input.Split(new[] { 'H', 'V' }, StringSplitOptions.RemoveEmptyEntries)
.Sum(str => int.Parse(str));
The RegExp i would use (not tested) is:
((\d+)(?<type>[HV]))((\d+)\k<type>)*
Via \k you ensure that only Hs or Vs are in the string, but not mixed. The return value is probably an array, so that you easy can sum up the numbers.
精彩评论