开发者

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)

, "0342123456" (PhoneNumber)

, 129 (开发者_如何学GoGroup Number)

, "simnumber" (contact Name)


Regex escape characters are different depending on the language. Try this assuming that the middle 7 digits is the phone number.

\\"(\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).

AT+CPBR=1\r\r\n+CPBR: 1, "0342123456", 129, "simnumber"\r\n\r\nOK\r\n

With C# you can use the following

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.


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). In php you can do like this:

$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);

OUTPUT

string(10) "0342123456"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜