守着星空守着你
此正则表达式模式将匹配字符串中的所有单个数字:(".*?")|(\d+(.\d+)?)(".*?")匹配之类的东西 "123.45"(\d+(.\d+)?)匹配诸如123.45或之类的东西123从那里,您可以对每个匹配项进行简单的搜索和替换,以获得“干净”的数字。完整代码: var s = "703.36,751.36,\"1,788.36\",887.37,891.37,\"1,850.37\",843.37,\"1,549,797.36\",818.36,749.36,705.36,0.00,\"18,979.70\",934.37"; Regex r = new Regex("(\".*?\")|(\\d+(.\\d+)?)"); List<double> results = new List<double>(); foreach (Match m in r.Matches(s)) { string cleanNumber = m.Value.Replace("\"", ""); results.Add(double.Parse(cleanNumber)); } Console.WriteLine(string.Join(", ", results));输出:703.36, 751.36, 1788.36, 887.37, 891.37, 1850.37, 843.37, 1549797.36, 818.36, 749.36, 705.36, 0, 18979.7, 934.37
温温酱
使用跟踪状态的解析器类型的解决方案来解决这个问题会更简单。正则表达式适用于常规文本,只要您有上下文,就很难用正则表达式解决。像这样的东西会起作用。internal class Program{ private static string testString = "703.36,751.36,\"1,788.36\",887.37,891.37,\"1,850.37\",843.37,\"1,549,797.36\",818.36,749.36,705.36,0.00,\"18,979.70\",934.37"; private static void Main(string[] args) { bool inQuote = false; List<string> numbersStr = new List<string>(); int StartPos = 0; StringBuilder SB = new StringBuilder(); for(int x = 0; x < testString.Length; x++) { if(testString[x] == '"') { inQuote = !inQuote; continue; } if(testString[x] == ',' && !inQuote ) { numbersStr.Add(SB.ToString()); SB.Clear(); continue; } if(char.IsDigit(testString[x]) || testString[x] == '.') { SB.Append(testString[x]); } } if(SB.Length != 0) { numbersStr.Add(SB.ToString()); } var nums = numbersStr.Select(x => double.Parse(x)); foreach(var num in nums) { Console.WriteLine(num); } Console.ReadLine(); }}