참조 블로거: Unity는 문자열 번호를 추출하고 수정 후 문자열을 반환합니다._unity 문자열은 숫자를 추출합니다_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.07883658697039622습도 + 58.427987942231184"
인쇄 결과: z = 0.085LAI + 0.032Aspect + 0.078Humidity + 58.427