2

I parse simple json object:

{"phone":"8 920 034-00-88"}

To get phone number i use code below:

string phoneStr = @"{""phone"":""8 920 034-00-88""}";
string searchPattern = @"{\s*""phone""\s*:\s*""(?<phone>.+)""\s*}";

Match match = Regex.Match(phoneStr, searchPattern);
if (match.Success)
   Console.WriteLine("Phone number:{0}", match.Groups["phone"].Value);
else
   Console.WriteLine("Phone number did not match");

I get result like: '8 920 034-00-88', but i need only digit symbol in phone number without whitespace and '-' like: '89200340088'. Can i get this result use only Regex?

2
  • 1
    Don't do that. You should use a JSON parser. Commented Aug 17, 2015 at 17:19
  • 1
    var digits = new string("{\"phone\":\"8 920 034-00-88\"}".Where(char.IsDigit).ToArray());? Commented Aug 17, 2015 at 17:20

2 Answers 2

2

You can use Regex.Replace and replace everything that isn't a digit:

var result = new Regex(@"\D").Replace(phoneStr, string.Empty);
Sign up to request clarification or add additional context in comments.

Comments

0

Try this to remove whitespaces, hyphens and apostrophes

var value = Regex.Replace("8 920 034 - 00 - 88", @"\s|\-|'", "");

Result: value = 89200340088

1 Comment

Replace any non-digit is far safer, as long as you want any kind of padding removed. Some places use / as separator as well, there's no end to the delimiters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.