正则表达式提取电话号码
本文关键字:电话号码 提取 正则表达式 | 更新日期: 2023-09-27 18:32:04
<CallInfo info: from '600000000', to '800000000', forwardedFrom '', display '', category '1', tollCategory '2',callingNumberRestricted false, custom '', receivingComplete true> -- (SUCCESS)
我有一个巨大的文本文件,里面有很多这样的行。有人可以帮我如何构建正则表达式,以便我可以提取数字'800000000'
吗?
发件人和收件人电话号码将不同。
我总是需要to
的号码
目前,我正在空白处拆分行,然后遍历我认为效率非常低的数组。
首先,您必须获得to-Number的整个匹配项:
, to '[0-9]{9}',
之后,您必须从比赛中获得一组。你最好像这样命名组:
, to '(?<toNumber>[0-9]{9})',
获取电话号码的实现可能如下所示:
string regex = ", to '(?<toNumber>[0-9]{9})',";
string text = "<CallInfo info: from '600000000', to '800000000', forwardedFrom '', display '', category '1', tollCategory '2',callingNumberRestricted false, custom '', receivingComplete true> -- (SUCCESS)";
string toNumber = string.Empty;
Match match = Regex.Match(text, regex);
if (match.Success)
{
toNumber = match.Groups["toNumber"].Value;
}
尝试to '('d{9})
。 这将匹配文本to '
后连续 9 位数字的任何序列,并将结果存储在第一个捕获组中。
这有效。不过,我不确定您的输入有多大变化...
string s = "<CallInfo info: from '600000000', to '800000000', forwardedFrom '', display '', category '1', tollCategory '2',callingNumberRestricted false, custom '', receivingComplete true> -- (SUCCESS)";
Regex r = new Regex("^<CallInfo.* to '(''d{9})'");
var match = r.Match(s);
var number = match.Groups[1];
看起来很简单。我会从您的文件中获取一个"示例"行并将其转换为正则表达式,用指示您感兴趣的数据类型的特殊字符标记和替换真实数据。具体来说,您说要捕获"收件人"电话号码:
@"^<CallInfo info: from ''d{1,9}', to '(?<toNumber>'d{1,9})', forwardedFrom '.*?', display '.*?', category '.*?', tollCategory '.*?', callingNumberRestricted (?:true|false), custom '.*?', receivingComplete (?:true|false)> -- '(SUCCESS')$"
使用 Regex.Match() 针对此模式运行整个文件,您可以使用以下代码生成"to"数字列表:
List<string> toNumbers = Regex.Match(contentsOfFile, pattern).Groups["toNumber"].ToList();
您可以通过简单的解析将数字转换为实际的数值:
List<ulong> toNumbersAsLongs = toNumbers.Select(s=>ulong.Parse(s)).ToList();
如果您需要此文件中的任何其他数据,只需将该字段括在带有括号的模式中,并使用?<captureName>
约定为其命名。