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 &
On this way you can read each line of the text file. You fill the json with Key = until the ":" Value= From the ":"
Dictionary<string, string> yourDictionary = new Dictionary<string, string>();
string pathF = "C:\\fich.txt";
StreamReader file = new StreamReader(pathF, Encoding.Default);
string step = "";
List<string> stream = new List<string>();
while ((step = file.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(step))
{
yourDictionary.Add(step.Substring(0, step.IndexOf(':')), step.Substring(step.IndexOf(':') + 1));
}
}
Here's one way to do it with regex (comments in code):
string[] lines = {@"Input File : 'D:\myfile.wav'", @"Duration: 00:00:18.57"};
Regex regex = new Regex("^[^:]+");
Dictionary<string, string> dict = new Dictionary<string, string>();
for (int i = 0; i < lines.Length; i++)
{
// match in the string will be everything before first :,
// then we replace match with empty string and remove first
// character which will be :, and that will be the value
string key = regex.Match(lines[i]).Value.Trim();
string value = regex.Replace(lines[i], "").Remove(0, 1).Trim();
dict.Add(key, value);
}
It uses pattern ^[^:]+
, which is negated class technique to match everything unless specified character.
Basically, you do not want to split your entire string, but to skip all the content before encountering first ':' char plus one symbol (':' itself).
var data = line.Substring(line.IndexOf(':') + 1);
Or if you really want solution with Split:
var data = string.Join(":", line.Split(':').Skip(1));
Here, we first split the string into array, then skip one element (the one we are trying to get rid of), and finally construct a new string with ':' between elements in the array.
you need to read put information to String Line
after that, do this.
String Key = Line.Split( ':' )[0];
String Value = Text.Substring( Key.Length + 1, Text.Length - Property.Length - 1 );
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: :