字符串解析
今天做自定义公式,然后要把公式中的变量和运算符找出来.
在这记录下下.
/// <summary> /// 将公式表达式进行解析. /// </summary> /// <returns></returns> public List<string[]> StrAnalyse(string strFormula) { Regex RegexSplit;// MatchCollection mMactchCol; var lstStrYsf = new List<string[]>(); //存放每个字符的 值,序号,类型(.+号表示运算符,a表示名称) RegexSplit = new Regex(@"\s"); strFormula = RegexSplit.Replace(strFormula, "");//去除空格 //筛选出运算符 RegexSplit = new Regex(@"\W"); mMactchCol = RegexSplit.Matches(strFormula); foreach (Match mMatch in mMactchCol) { var tempMessage = new string[3]; tempMessage[0] = mMatch.ToString(); tempMessage[1] = mMatch.Index.ToString(); tempMessage[2] = "+"; lstStrYsf.Add(tempMessage); } //筛选出名称(字母数字下划线) RegexSplit = new Regex(@"\w"); mMactchCol = RegexSplit.Matches(strFormula); foreach (Match mMatch in mMactchCol) { string[] tempMessage = new string[3]; tempMessage[0] = mMatch.ToString(); tempMessage[1] = mMatch.Index.ToString(); tempMessage[2] = "a"; lstStrYsf.Add(tempMessage); } //排序(按原字符串中的顺序排序) string[][] strArray = new string[lstStrYsf.Count][]; for (int i = 0; i < lstStrYsf.Count; i++) { for (int j = 0; j < lstStrYsf.Count; j++) { if (Convert.ToInt16(lstStrYsf[j][1]) == i) strArray[i] = lstStrYsf[j]; } } //再次组合成字符串数组,把名称和其余符号分开并标记 List<string[]> lstResult = new List<string[]>(); string tap = strArray[0][2]; string[] strSum = new string[2]; strSum[1] = tap; foreach (string[] s in strArray) { if (tap == s[2]) strSum[0] += s[0]; else { tap = s[2]; Array temp = Array.CreateInstance(typeof(string), 2); strSum.CopyTo(temp, 0); lstResult.Add((string[])temp); strSum[0] = s[0]; strSum[1] = tap; } } lstResult.Add(strSum); return lstResult; }
看到的朋友有更好的方法或者我的有什么问题,欢迎指点批评.