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 &
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.
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: :