如何用Regex提取Re:后左括号前的目标名称?
问题解决方案
问题描述
现有文本内容:
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Re: Krishna P Mohan (31231231 / NA0031212301) Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
需要提取Re:之后、左括号(之前的名称「Krishna P Mohan」,但当前正则代码提取了整行内容,不符合需求。
当前使用的代码:
var regex = new Regex(@"[\n\r].*Re:\s*([^\n\r]*)"); var fullNameText = regex.Match(extractedDocContent).Value;
解决方法
正则表达式调整
把正则改成@"Re:\s*([^(]+)\s*\(",核心改动:
([^(]+):匹配除左括号外的所有字符,精准锁定名称部分\s*\(:匹配名称后到左括号之间的空白,确保不会包含括号内容
修正后的代码
var regex = new Regex(@"Re:\s*([^(]+)\s*\("); var match = regex.Match(extractedDocContent); var fullNameText = match.Success ? match.Groups[1].Value.Trim() : string.Empty;
- 用
match.Groups[1].Value获取捕获组的内容,而不是Match.Value(后者是整个匹配的文本) - 加上
.Trim()可以去除名称两端可能存在的空白字符
内容的提问来源于stack exchange,提问作者krishna mohan
相关产品推荐
相关产品推荐

