对于包含字符和数字的字符串,如何仅对所有数字加1 [英] For a string containing characters and numbers, how to add 1 to all numbers only

查看:309
本文介绍了对于包含字符和数字的字符串,如何仅对所有数字加1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的帮助! 我有一个来自路径文件的字符串列表:

Thanks for helping me! I have a string list coming from a path file:

Data ="M311.97458,250.39993 L213.97533,248.39996 222.37435,216.7998 C222.37435,216.7998 ...... 589.5753,173.99994 593.1753,179.9999 ...... 334.3039,253.21373 311.97458,250.39993 z("......."用于表示不必要的数字")

Data="M311.97458,250.39993 L213.97533,248.39996 222.37435,216.7998 C222.37435,216.7998 ......589.5753,173.99994 593.1753,179.9999 ......334.3039,253.21373 311.97458,250.39993 z" (the "......." is used for representing uncessary number")

如您所见,字符(例如"M"和"C")具有某些特殊含义,并且数字对用于坐标.我想在数据"中的每个数字上加1,而不更改任何其他内容.我该如何使用C#做到这一点?我想.split()是有用的,但数据"仅对于.split()来说太难了

As you can see, the characters (like "M" and "C") have some special meaning, and number pairs are for cooridinate. I want to add 1 to each numbers in "Data" without changing any other things. How can I do that with C#? I guess a .split() is useful but the "Data" is too hard for .split() only

谢谢!

推荐答案

您可以使用Regex识别字符串中的数字,并将其替换为新值.例如;

You can use Regex to identify the numbers within the string and replace them with a new value. For example;

var data = @"M311.97458,250.39993 L213.97533,248.39996 222.37435,216.7998 C222.37435,216.7998 ......589.5753,173.99994,593.1753,179.9999......334.3039,253.21373 311.97458,250.39993 z";            
var replaced = Regex.Replace(data, "((?=[^, ])\\d+\\.\\d+)", (match) => (double.Parse(match.Value) + 1).ToString());
// output: M312.97458,251.39993 L214.97533,249.39996 223.37435,217.7998 C223.37435,217.7998 ......590.5753,174.99994,594.1753,180.9999......335.3039,254.21373 312.97458,251.39993 z

因此,这里的Regex模式通过查找不是逗号或空格并且是带小数位的数字来识别字符串中的数字(因此,它不适用于整数,但是您可以根据需要进行调整).然后有效地在Regex.Replace中,我们遍历每个匹配项,并使用

So here the Regex pattern is identifying the numbers within the string by finding anything that's not a comma or space and is numeric with a decimal place in (so it won't work for integers, but you can adapt if required). Then effectively in the Regex.Replace we're looping through each match, and using a MatchEvaluator to add one to the number and return it to form the new string.

这篇关于对于包含字符和数字的字符串,如何仅对所有数字加1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆