参考博主:unity 提取字符串数字修改后返回字符串_unity string提取数字_lvcoc的博客-CSDN博客
正数和浮点数的 正则表达式
//正则表达式
//const string pattern = @"\d+";//表达1位或多位的整数数字
const string pattern = @"\d+\.\d+";//表达1位或多位的浮点数字
/// <summary>
///
/// </summary>
/// <param name="atr01"></param>
/// <returns></returns>
private string ChangeString(string atr01)
{
string atr = atr01;
var a = Regex.Matches(atr, pattern).Cast<Match>().Select(m => m.Index).ToArray();
var b = Regex.Matches(atr, pattern).Cast<Match>().Select(m => m.Value).ToArray();
string[] tmp = Regex.Matches(atr, pattern).Cast<Match>().Select(m => m.Value).ToArray();
for (int y = 0; y < b.Length; y++)
{
tmp[y] = double.Parse( tmp[y]).ToString("f3");
}
for (int z = a.Length - 1; z >= 0; z--)
{
var length = b[z].Length;
string t1 = atr.Substring(0, a[z]);
string t2 = atr.Substring(a[z] + length, atr.Length - a[z] - length);
atr = string.Format("{0}{1}{2}", t1, tmp[z], t2);
}
return atr;
}
示例:
void Awake()
{
ChangeString("z = 0.08596656649430752LAI + 0.032354611497339036Aspect + 0.07883658697039622Humidity + 58.427987942231184");
}
//正则表达式
//const string pattern = @"\d+";//表达1位或多位的整数数字
const string pattern = @"\d+\.\d+";//表达1位或多位的浮点数字
/// <summary>
///
/// </summary>
/// <param name="atr01"></param>
/// <returns></returns>
private string ChangeString(string atr01)
{
string atr = atr01;
var a = Regex.Matches(atr, pattern).Cast<Match>().Select(m => m.Index).ToArray();
var b = Regex.Matches(atr, pattern).Cast<Match>().Select(m => m.Value).ToArray();
string[] tmp = Regex.Matches(atr, pattern).Cast<Match>().Select(m => m.Value).ToArray();
for (int y = 0; y < b.Length; y++)
{
tmp[y] = double.Parse( tmp[y]).ToString("f3");
}
for (int z = a.Length - 1; z >= 0; z--)
{
var length = b[z].Length;
string t1 = atr.Substring(0, a[z]);
string t2 = atr.Substring(a[z] + length, atr.Length - a[z] - length);
atr = string.Format("{0}{1}{2}", t1, tmp[z], t2);
}
return atr;
}
用例:“z = 0.08596656649430752LAI + 0.032354611497339036Aspect + 0.07883658697039622Humidity + 58.427987942231184”文章来源:https://www.toymoban.com/news/detail-677220.html
打印结果:z = 0.085LAI + 0.032Aspect + 0.078Humidity + 58.427文章来源地址https://www.toymoban.com/news/detail-677220.html
到了这里,关于unity 提取 字符串中 数字 修改后返回 字符串的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!