unity 提取 字符串中 数字 修改后返回 字符串

参考博主:unity 提取字符串数字修改后返回字符串_unity string提取数字_lvcoc的博客-CSDN博客

 正数和浮点数的 正则表达式

//正则表达式
	//const string pattern = @"\d+";//表达1位或多位的整数数字  
	const string pattern = @"\d+\.\d+";//表达1位或多位的浮点数字  
	/// 
	/// 
	/// 
	/// 
	/// 
	private string ChangeString(string atr01)
	{
		string atr = atr01;
		var a = Regex.Matches(atr, pattern).Cast().Select(m => m.Index).ToArray();
		var b = Regex.Matches(atr, pattern).Cast().Select(m => m.Value).ToArray();
		string[] tmp = Regex.Matches(atr, pattern).Cast().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位或多位的浮点数字  
	/// 
	/// 
	/// 
	/// 
	/// 
	private string ChangeString(string atr01)
	{
		string atr = atr01;
		var a = Regex.Matches(atr, pattern).Cast().Select(m => m.Index).ToArray();
		var b = Regex.Matches(atr, pattern).Cast().Select(m => m.Value).ToArray();
		string[] tmp = Regex.Matches(atr, pattern).Cast().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”

打印结果:z = 0.085LAI  +  0.032Aspect  +  0.078Humidity  +  58.427

你可能感兴趣的:(unity,正则表达式,unity,servlet,游戏引擎)