简体   繁体   中英

I want to get a specific part of a huge string

I have a string, that contain some message, inside of this, there's a telephone number, I want to get that specific part.

I tried using string Split, but to no avail.


Contato via web site

 Segue abaixo os dados preenchidos pelo visitante:

 Nome: Nome Qualquer

 E-mail: exemplod@exemplo.com 

 Telefone: (99) 99999-9999 

 Mensagem: Mensagem enviada



I want to use someway to retrieve the "Telefone" part of the string, preferably only the digits, like "(99) 99999-9999", or already formatted to "99999999999".

While Denis answer seems fine for the time being that number may change the spaces or perhaps the format of the number may change also. So the approach i would take is using regex. I made 2 regex, one to match that exact format number and one that can match more numbers, i took into account that they may be international too.

The specific regex would be:

\([0-9]{2}\)\s[0-9]{5}-[0-9]{4}

And the more broad one:

\+?(\([0-9]+\))?\s?[0-9\-]+

The usage of this is:

Regex reg = new Regex(@"\([0-9]{2}\)\s[0-9]{5}-[0-9]{4}");
var match = reg.Match("yourinput").Value;

Assuming you data has always this exact format, you can try something like this:

        string s = "Contato via web site Segue abaixo os dados preenchidos pelo visitante:    Nome: Nome Qualquer E - mail: exemplod @exemplo.com    Telefone: (99) 99999 - 9999 Mensagem: Mensagem enviada";
        int start = s.IndexOf("Telefone: ") + 10;
        int end = s.IndexOf("Mensagem");
        string phonenumber = s.Substring(start, end - start);

this will find the part of the string containing "Telefone: " and cut the number out of it after that. You could also look for a linebreak after the start

I think the best way, would be using Regex. So it should something simple like this, if the only digits in your text are those for the phone.

It would be like :

string regex = @"/[0-9]/gm";
MatchCollection matchColl = Regex.Matches(YourText, regex);

Then MatchCollection got all the digits just loop over it to inspect each value if you want.

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