Reputation: 33
I am using a flat text file as a database and so i need to be able to parse a .txt. The first thing i need to do is be able to pull out the exact string i'm looking for which i am confused about. The other answers i have seen to this the strings are the same every time... but i am looking for how to pull out a text for example between (beginning) and (end) where everything in between is a different length every time. any help? Here is an example of what i want
String line = sr.ReadToEnd();
// line to get all the text from my file
string whatIWant = stringEditor("beginning", "end", line);
string whatIWant(string first, string second, string whatToParse)
{
//what do I put here to return
//the text from line between first and second
return whatever;
}
Upvotes: 0
Views: 119
Reputation: 7459
Took the solution from this answer , on how to extend the native string class to get a string betwen to strings.
Create the method Between in all strings:
public static class Ext
{
public static string Between(this string source, string left, string right)
{
return System.Text.RegularExpressions.Regex.Match(
System.Text.RegularExpressions.Regex.Excape(source),
string.Format("{0}(.*){1}", left, right))
.Groups[1].Value;
}
}
Then it gets really easy:
"beginning123456end".Between("beginning", "end")
123456
If you're always using beginning and end, let's go further:
public static class Ext
{
public static string BetweenBeginningAndEnd(this string source)
{
return System.Text.RegularExpressions.Regex.Match(
System.Text.RegularExpressions.Regex.Excape(source),
string.Format("{0}(.*){1}", "beginning", "end"))
.Groups[1].Value;
}
}
"beginning123456end".BetweenBeginningAndEnd()
123456
EDIT: As @codenoire said, you'll also need to escape possible Regex characters
Upvotes: 2
Reputation: 11090
Get the index of beginning and the index of end, then use substring to get the the string using the indexes.
string whatIWant(string beginning, string end, string whatToParse)
{
return whatToParse.Substring(whatToParse.IndexOf(beginning) + beginning.Length,whatToParse.IndexOf(end) -(whatToParse.IndexOf(beginning) + beginning.Length));
}
Upvotes: 1
Reputation: 442
You should use String.Substring()
string whatIWant(string first, string second, string whatToParse)
{
return whatToParse.Substring(first.Length, whatToParse.Length - first.Length - second.Length);
}
DotNetFiddle: https://dotnetfiddle.net/h5lNIB
Upvotes: 3