Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Get line of multiline String starting with specific word

Tags:

c#

regex

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";
        }
    }
like image 854
Orsinus Avatar asked Feb 10 '23 10:02

Orsinus


2 Answers

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

like image 90
hwnd Avatar answered Feb 11 '23 23:02

hwnd


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.

like image 28
Dzienny Avatar answered Feb 11 '23 23:02

Dzienny