简体   繁体   中英

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 (Group 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM