[英]Regex to extract phone number
<CallInfo info: from '600000000', to '800000000', forwardedFrom '', display '', category '1', tollCategory '2',callingNumberRestricted false, custom '', receivingComplete true> -- (SUCCESS)
我有一個很大的文本文件,上面有很多行。 有人可以幫我建立正則表達式,以便提取號碼'800000000'
嗎?
從和到電話號碼會不同 。
我總是需要它由follwed數量to
目前,我正在空行處分割行,然后遍歷數組,感覺效率很低。
嘗試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()按照此模式運行整個文件,可以使用以下代碼生成“收件人”數字的列表:
List<string> toNumbers = Regex.Match(contentsOfFile, pattern).Groups["toNumber"].ToList();
您可以通過簡單的解析將數字轉換為實際的數值:
List<ulong> toNumbersAsLongs = toNumbers.Select(s=>ulong.Parse(s)).ToList();
如果您需要此文件中的其他任何數據,只需將該字段括在括號中並使用?<captureName>
約定?<captureName>
。
首先,您必須獲得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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.