[英]create regex to Extract the phone number from string
I have a string in the following format that contains a index number, phone number, group Number and contact Name.我有一个以下格式的字符串,其中包含索引号、电话号码、组号和联系人姓名。 Can you create some regex to extract all from follwing string?您可以创建一些正则表达式来从以下字符串中提取所有内容吗?
"AT+CPBR=1\r\r\n+CPBR: 1, "0342123456", 129, "simnumber"\r\n\r\nOK\r\n"
Breakdown:分解:
"AT+CPBR=1\r\r\n+CPBR: 1
(Index Number) "AT+CPBR=1\r\r\n+CPBR: 1
(索引号)
, "0342123456"
(PhoneNumber) , "0342123456"
(电话号码)
, 129
(Group Number) , 129
(组号)
, "simnumber"
(contact Name) , "simnumber"
(联系人姓名)
Regex escape characters are different depending on the language.正则表达式转义字符因语言而异。 Try this assuming that the middle 7 digits is the phone number.假设中间 7 位数字是电话号码,请尝试此操作。
\\"(\d+)\\"
this will return这将返回
0342123456
In the capture group.在捕获组中。
Update更新
In re-reading your question I'm guessing that the escape sequences are escaped in your input string so that your real input is (\r & \n left in place for simplicity).在重新阅读您的问题时,我猜测转义序列在您的输入字符串中被转义,因此您的真实输入是(为简单起见,保留在原位 \r & \n )。
AT+CPBR=1\r\r\n+CPBR: 1, "0342123456", 129, "simnumber"\r\n\r\nOK\r\n
With C# you can use the following使用 C# 您可以使用以下
string s = "AT+CPBR=1\r\r\n+CPBR: 1, \"0342123456\", 129, \"simnumber\"\r\n\r\nOK\r\n";
Regex rx = new Regex(@": (\d), ""(\d+)"", (\d+), ""(\w+)""");
Match m = rx.Match(s);
Console.WriteLine(m.Groups[0]);
Console.WriteLine(m.Groups[1]);
Console.WriteLine(m.Groups[2]);
Console.WriteLine(m.Groups[3]);
Console.WriteLine(m.Groups[4]);
This will result in这将导致
1
0342123456
129
simnumber
Remember that Groups[0] contains the entire match including the quotes.请记住, Groups[0] 包含整个匹配项,包括引号。
May I ask why do you want to use regex to extract phone # in above string.请问你为什么要使用正则表达式来提取上面字符串中的电话号码。 Why not use a variant of split()
or explode()
function on your text using space character and from the resulting string array take element # 2 (3rd element).为什么不在使用空格字符的文本上使用split()
或explode()
function 的变体,并从生成的字符串数组中获取元素#2(第三个元素)。 In php you can do like this:在 php 你可以这样做:
$arr = (explode(' ', '"AT+CPBR=1\r\r\n+CPBR: 1, \"0342123456\", 129, \"simnumber\"\r\n\r\nOK\r\n"'));
$phoneNo = trim($arr[2], '\",');
var_dump($phoneNo);
string(10) "0342123456"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.