RegexParseException报错及最长相同元音序列计算异常求助
问题排查与修复
核心问题分析
- 正则表达式语法错误:当
lastVowel为空字符串时,构造的正则表达式变成了+,这是无效语法——量词+必须跟在可匹配的字符/组后面,直接写+会触发RegexParseException。 lastVowel变量逻辑完全错误:这个变量的遍历逻辑混乱,既不能跟踪当前连续元音,也无法记录有效匹配目标,最终经常为空,导致正则匹配失效。- 移除辅音的逻辑冗余:手动遍历字符判断是否为辅音的写法可以简化,用正则替换更简洁高效。
修复后的代码方案
这里提供两种可靠实现:
方案1:正则实现(代码简洁)
using System; using System.Text.RegularExpressions; RemoveConsonantsAndFindLongestVowelSequence("musicisthebestbeatofall"); RemoveConsonantsAndFindLongestVowelSequence("dontworrybehoppynow"); static void RemoveConsonantsAndFindLongestVowelSequence(string input) { // 移除所有辅音,仅保留元音 string onlyVowels = Regex.Replace(input, "[^aeiouAEIOU]", ""); if (string.IsNullOrEmpty(onlyVowels)) { Console.WriteLine(0); return; } // 匹配所有连续相同的元音序列 MatchCollection sequences = Regex.Matches(onlyVowels, @"([aeiou])\1+", RegexOptions.IgnoreCase); int maxLength = 1; // 存在元音时最小长度为1 foreach (Match match in sequences) { if (match.Length > maxLength) { maxLength = match.Length; } } Console.WriteLine(maxLength); }
方案2:手动遍历(性能更优)
using System; using System.Text; RemoveConsonantsAndFindLongestVowelSequence("musicisthebestbeatofall"); RemoveConsonantsAndFindLongestVowelSequence("dontworrybehoppynow"); static void RemoveConsonantsAndFindLongestVowelSequence(string input) { // 过滤出所有元音 StringBuilder onlyVowels = new StringBuilder(); foreach (char c in input) { if ("aeiouAEIOU".Contains(c)) { onlyVowels.Append(c); } } string vowelStr = onlyVowels.ToString(); if (string.IsNullOrEmpty(vowelStr)) { Console.WriteLine(0); return; } // 查找最长连续相同元音的长度 int maxLength = 1; int currentLength = 1; char currentVowel = char.ToLower(vowelStr[0]); for (int i = 1; i < vowelStr.Length; i++) { char current = char.ToLower(vowelStr[i]); if (current == currentVowel) { currentLength++; maxLength = Math.Max(maxLength, currentLength); } else { currentVowel = current; currentLength = 1; } } Console.WriteLine(maxLength); }
测试验证
- 输入
musicisthebestbeatofall:处理后元音序列包含连续3个e,输出结果为3,符合预期。 - 输入
dontworrybehoppynow:最长连续元音为2个o,输出结果为2,符合预期。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

