如何检查字符串是否含字母及有效文本?C#代码优化需求
解决方案:统计包含有效单词的错误字符串
要实现只统计包含有效单词的错误字符串,排除纯数字、空格、符号或无意义字符组合的情况,你可以通过正则表达式匹配字母序列来实现核心判断逻辑。
核心判断逻辑
先实现一个辅助方法,用来验证字符串是否包含至少一个由字母组成的有效单词:
private bool IsValidErrorString(string errorStr) { if (string.IsNullOrWhiteSpace(errorStr)) return false; // 匹配至少一个Unicode字母(支持多语言),排除纯数字/符号/空白的情况 return System.Text.RegularExpressions.Regex.IsMatch(errorStr.Trim(), @"\p{L}+"); }
string.IsNullOrWhiteSpace直接排除空字符串、全空格/制表符的情况\p{L}是Unicode正则表达式,匹配任何语言的字母(如果只需要英文,可替换为[a-zA-Z]+)Trim()先去除字符串首尾空白,避免因首尾空格导致的误判
修改后的完整代码
把原来的计数判断替换成调用这个辅助方法,同时修复原代码的计数累计bug,修改后的highORlow方法如下:
/** Find the highest/lowest amount of errors/solutions/suggestions/comments. * If it's ASC then return the lowest to highest. * If it's DESC then return the highest to lowest. * Return a list with LOGS in the correct order. * */ public List<LOG> highORlow(string asc_desc, string category) { int[] array = new int[this.Count()]; for(int i = 0; i < this.Count(); i++) { int count = 0; // 移到内层循环外,确保每个条目单独统计 var notarisedList = this.ElementAt(i).getNotarised(); for(int j = 0; j < notarisedList.Count(); j++) { string errorStr = notarisedList.ElementAt(j).getError(); if (IsValidErrorString(errorStr)) { ++count; } } array[i] = count; } // 补充排序与返回逻辑(原代码未实现) var sortedLogs = this.Zip(array, (log, count) => new { Log = log, Count = count }) .OrderBy(x => x.Count) // ASC排序,DESC则用OrderByDescending .Select(x => x.Log) .ToList(); return sortedLogs; } private bool IsValidErrorString(string errorStr) { if (string.IsNullOrWhiteSpace(errorStr)) return false; return System.Text.RegularExpressions.Regex.IsMatch(errorStr.Trim(), @"\p{L}+"); }
额外说明
- 原代码中
count变量定义在循环外,会累计所有条目的计数,现在调整后每个条目单独统计自身的有效错误数 - 如果需要更严格的“可读语句”判断,可以调整正则规则,比如要求至少两个单词:
@"\p{L}+\s+\p{L}+",但这会排除单单词的有效字符串,可根据需求选择 - 若不需要支持多语言,把正则替换为
@"[a-zA-Z]+"即可,仅匹配英文字母
内容的提问来源于stack exchange,提问作者Anda
相关产品推荐
相关产品推荐

