简体   繁体   中英

C# get username from string. split

Hello everybody i want to split text and get value

How i can get Example from here:

L 02/28/2012 - 04:52:05: "Example<2><VALVE_ID_PENDING><>" entered the game

i tried whole bunch of stuff but it was very difficult for me? Can anybody help me?

// say you have your text in the text variable
var yourExtractedText = text.Split('"').Split('<')[0];

Careful though, this will cause exceptions if the format of the string changes.

Could try something like

string s = "L 02/28/2012 - 04:52:05: \"Example<2><VALVE_ID_PENDING><>\" entered the game";
int start = s.IndexOf('"')+1;
int end = s.IndexOf('<');
var un = s.Substring(start, end-start);

You need to give character before the start of the output string you do myString.Split('"'); you will get array of strings which is

string[] myStringArray = myString.Split('"');

myStringArray[0]  contains L 02/28/2012 - 04:52:05: 
myStringArray[1]  contains Example<2><VALVE_ID_PENDING><>" 
myStringArray[2]  contains entered the game 

You can apply this logic and build the required string.

Remember to use StringBuilder while constructing the string again.

You might consider using regular expressions to find what you are looking for:

Match match = Regex(inputString, "\"([\w\s]+)<");
if (match.Success) {
    String username = match.Groups[1].Value;
}

Take care to include the information you know has to be present. For example if you know that your username starts with a quotation mark, consists only of word characters and whitespace and ends with a angle-bracket delimited number, you might instead write:

Match match = Regex(inputString, "\"([\w\s]+)<[0-9]+>");
if (match.Success) {
    String username = match.Groups[1].Value;
}

Here you are:

        private void button2_Click(object sender, EventArgs e)
        {
            string temp = GetExample("L 02/28/2012 - 04:52:05: \"Example<2><VALVE_ID_PENDING><>\" entered the game");
        }

    private string GetExample(string text)
    {
        int startIndex = text.IndexOf('"');
        int endIndex = text.IndexOf('<');

        return text.Substring(startIndex + 1, endIndex - startIndex - 1);
    }

Don't forget that before " in a string should come a \\ .

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