I have a multiline string, say
abcde my first line
fghij my second line
klmno my third line
All of this is one String, but what I want to do now is to get the content (substring) of this string which is starting with a specific word, for example "fghij". So if I do a method and pass "fghij" to it, it should return me "fghij my second line" in that case.
The following I tried, but it does not 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";
}
}
The *
operator is currently quantifying the last letter in mySubstring
. You need to precede the operator with .
to eat up the rest of the characters on the given line. No need for grouping either.
Match m = Regex.Match(myInput, "^" + mySubstring + ".*", RegexOptions.Multiline);
if (m.Success) {
// return m.Value
}
Ideone Demo
You are almost there, just change the *
char to [^\r\n]+
Match m = Regex.Match(myInput, "^(" + mySubstring + "[^\n\r]+)", RegexOptions.Multiline);
[^\r\n]+
will match any character, but \r
and \n
, which are used to mark a new line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With