How do I extract PART of a specific string from a huge chunk of ugly strings?

前端 未结 1 1568
情歌与酒
情歌与酒 2021-01-29 10:59

I have a variable that has all the data source of a web page. It\'s a large string with lots of words, strings, special characters, etc.

I want to go through this variab

1条回答
  •  再見小時候
    2021-01-29 12:02

    Something like this should get you started work

            string pattern = @"https://company.zendesk.com/api/v2/tickets/\d+.json";
            Regex regex = new Regex(pattern);
            MatchCollection mc = regex.Matches("input string here");
    
            foreach(Match m in mc)
            {
                Console.Write(m.Value);
            }
    

    @"https://company.zendesk.com/api/v2/tickets/\d+.json";

    take note of the bolded parts. the @ means that it's a literal string, so you don't have to double-escape your \. the \d is a stand-in for any digit. the + means the previous character occurs 1 or more times. * would mean that it occurs 0 or more times.

    here's a reference on how you can futher customize the pattern http://msdn.microsoft.com/en-us/library/az24scfc.aspx

    To get just the ticket numbers, you can put the "\d+" in parenthesis
    https://company.zendesk.com/api/v2/tickets/(\d+).json"

    and then your match will have a property called Groups your ticket number will be one of those groups

                Console.Write(m.Groups[i].Value);
    

    At that point, you can filter out the full match group from the ticket number of groups using a number of heuristics including but limited to the string length, or you can use another regex.

    0 讨论(0)
提交回复
热议问题