C # Get a string of a multi-line string starting at a specific word
I have a multi-line string, say
abcde my first line
fghij my second line
klmno my third line
It's all one line, but now I want to get the content (substring) of that line that starts with a specific word like "fghij". So if I make a method and pass "fghij" to it, it should return "fghij my second line" to me in this case.
The next thing I tried, but it doesn't work, unfortunately m.Success is always false:
String getLineBySubstring(String myInput, String mySubstring)
{
Match m = Regex.Match(myInput, "^(" + mySubstring + "*)", RegexOptions.Multiline);
Console.WriteLine("getLineBySubstring operation: " + m.Success);
if (m.Success == true)
{
return m.Groups[0].Value;
}
else
{
return "NaN";
}
}
source to share
The operator *
is currently quantizing the last letter in mySubstring
. You need to put before the operator .
to eat the rest of the characters on the given line. No need to group.
Match m = Regex.Match(myInput, "^" + mySubstring + ".*", RegexOptions.Multiline);
if (m.Success) {
// return m.Value
}
source to share
If you need to check that a string starts with some substring, you should avoid Regex. Just split the whole line into lines and check each line with StartsWith.
String getLineBySubstring(String myInput, String mySubstring)
{
string[] lines = myInput.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
if (line.StartsWith(mySubstring))
return line;
return "NaN";
}
source to share