I have some code that reads a text file and sets it to a string. Each line of the text file contains separate data parameters that I a trying to extract. Here is an small ex
You can also use a regex to do this; it can handle more complex cases than the simple IndexOf
or Split
solutions, such as skipping whitespaces around the =
or not match certain patterns, or extract all the components found in a single line at once.
string partNum = Regex.Match(partData, @"=(.*)$", RegexOptions.Multiline).Groups[1].Value;
The regex will be slower for the simple case (such as just splitting on the =
), but if you actually want to process and extract data from a halfway complex pattern it will be more efficient and more concise as well.
Also, by checking the Success
property on the match, you could validate that the data is conforming to the expected pattern along the way without requiring any additional processing/verification logic.
Here's an example which extracts the parts before and after the = sign for each text line which is using the expected pattern in the string, and trims the parts along the way:
for (Match match = Regex.Match(partData, @"^\s*([^=]+?)\s*=\s*(.*?)\s*$", RegexOptions.Multiline);
match.Success;
match = match.NextMatch()) {
// this code runs for each line in your string which has the expected pattern
string key = match.Groups[1].Value;
string value = match.Groups[2].Value;
}
Edit: Here's a fiddle which does show how this code works with your sample data.