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";
        }
    }

      

+3


source to share


4 answers


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
} 

      



Perfect demonstration

+2


source


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

also \n

that are used to denote a newline.

+2


source


Try adding an ending line $

to your regex. Also *

associated with mySubstring

, indicates the repetition of the last character in mySubstring

you must have .*

to catch all possible ones.

Regex.Match(myInput, "^(" + mySubstring + ".*)$", RegexOptions.Multiline);

      

+1


source


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";            
    }

      

+1


source







All Articles