How to match the first occurrence of a character and split it

后端 未结 5 1289
忘掉有多难
忘掉有多难 2021-01-26 16:24

I have a text file from which I want to store Keys and Values in a String array.

In this case, Key is something like &

5条回答
  •  孤城傲影
    2021-01-26 16:43

    Using regular expression captures

    private static Regex _regex = new Regex(@"^([\p{L}_ ]+):?(.+)$");
    
    ....
    
    Match match = _regex.Match(line);
    if (match.Success)
    {
        string key = match.Groups[1].Captures[0].Value;
        string value = match.Groups[2].Captures[0].Value;
    }
    

    The regexp is a static member to avoid compiling it for every usage. The ? in the expression is to force lazy behavior (greedy is the default) and match the first :.

    Link to Fiddle.

    Edit

    I've updated the code and fiddle after your comment. I think this is what you mean:

    Key: Any letter, underscore and whitespace combination (no digits) Value: anything Separator between key and value: :

提交回复
热议问题