C#正则表达式匹配提取单引号内字符失败,求问题排查
问题分析与解决
你的代码存在两个关键问题:
正则未定义命名捕获组
postfix
你编写的正则(?<=\')(.*?)(?=\')仅用了正向前后断言捕获单引号间的内容,但没有给这个捕获的内容命名为postfix,导致match.Groups["postfix"]找不到对应分组,返回空值。修正后的正则需要添加命名捕获组:
Regex pattern = new Regex(@"(?<=\')(?<postfix>.*?)(?=\')");或者更简洁的写法,直接用命名捕获组包裹目标内容,省略前后断言:
Regex pattern = new Regex(@"'(?<postfix>.*?)'");类型转换的风险
测试字符串中单引号内的内容是字符'm',直接用int.Parse转换会抛出异常。如果你的场景里单引号内可能是字符或数字,需要先校验有效性再转换:if (int.TryParse(match.Groups["postfix"].Value, out int postFix)) { Debug.Log(postFix); } else { Debug.Log("单引号内不是有效整数"); }
修正后的完整代码示例:
var line = "[+] Random session part: 'm'"; Regex pattern = new Regex(@"'(?<postfix>.*?)'"); Match match = pattern.Match(line); if (match.Success) { string capturedValue = match.Groups["postfix"].Value; Debug.Log($"捕获到的值:{capturedValue}"); if (int.TryParse(capturedValue, out int postFix)) { Debug.Log($"转换后的整数:{postFix}"); } else { Debug.Log("无法转换为整数"); } } else { Debug.Log("未找到匹配内容"); }
内容的提问来源于stack exchange,提问作者Anand
相关产品推荐
相关产品推荐

