简体   繁体   中英

Most efficient way to parse a known format string

I have a string which is in the following format for example:

[ "{0}", "{1}", "{2}" ]

So I know there are always 3 parameters (of variable length) in that string format.

What is the most efficient way of parsing the string? (And maybe the shortest code along with it so I have to run some tests)

Thanks.

It can be done in many ways, using Regex class or string methods.

Here is how it can be done using Regex.Match :

        string s = @"[ ""some test"", ""another test string"", ""hi there!"" ]";
        string[] vars = Regex.Matches(s, @"""([^""]*)""")
            .Cast<Match>()
            .Select(m => m.Groups[1].Value)
            .ToArray();

Another way, using Regex.Split :

        vars = Regex.Split(s.Remove(s.Length - 3, 3).Remove(0, 3), @""",\s""");

Here is one way of doing it with string methods:

        vars = s.Substring(s.IndexOf("\"") + 1, s.LastIndexOf("\"") - 3)
                    .Split(new string[] {@""", """}, StringSplitOptions.None);

1st solution: I think this is simplest - Cut [ and ] (1st and last character) - Split by "," -> trim() -> get 3 parts - Remove redundant characters (like "{ and }") If you're sure that your expected strings don't contain " { } -> You can Remove them before split.

2nd solution: Use Regex

Example: Extract --> How Are You?

string stuff = @"""{How}"", ""{Are}"", ""{You?}""";
string[] answer = (stuff.Replace(@"""{", String.Empty).Replace(@"}""", String.Empty)).Split(',');

Now the variable answer holds the three words!

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