简体   繁体   中英

How to write regex that matches string from begining to first new line occurence?

how to match string from beginning to first new line feed.

Example if TextBox1.Text value is

'START: Milestone One\\r\\nFirst milestone is achieved in a week.'

Here is what I am trying:-

TextBox1.Text = Regex.Replace(TestBox1.Text, @"START: \w+\s?", "");

This Regex is finding first word only therefore replacing 'START: MileStone' with string.empty but leaving 'One' there.

I need to replace everything (including newline feed) before first newline feed.

You do not need a regex for that, just use IndexOf('\\n') + 1 :

var t = "START: Milestone One\r\nFirst milestone is achieved in a week.";
Console.WriteLine(t.Substring(t.IndexOf('\n') + 1).Trim());

See IDEONE demo

Result: First milestone is achieved in a week.

A regex will not be efficient here, but you can check it for yourself:

var text = Regex.Replace(t, @"(?>.+\r?\n)\s*", string.Empty);

See another demo

You can also use LINQ:

string str = "START: Milestone One\r\nFirst milestone is achieved in a week.";

string newStr = String.Join("", str.SkipWhile(c => c != '\n').Skip(1));

Console.WriteLine(newStr); // First milestone is achieved in a week.

To check if the input string is null or contains any \\n :

string newStr = (str?.Any(c => c == '\n')).GetValueOrDefault() ? String.Join("", str.SkipWhile(c => c != '\n').Skip(1)) : str;

I don't know if your anything like me but maybe you are practicing Regex and want to know how to make it happen with it. I'm very new at coding but I took your example and this is how I would make it happen.

    private void button1_Click(object sender, EventArgs e)
    {
        string test = "START: Milestone One\r\nFirst milestone is achieved in a week.";

        string final = Regex.Replace(test, ".*\\n", "START: ").ToString();
        MessageBox.Show(final); // START: First milestone is achieved in a week.
    }

Not sure if that helps your or not but thought I would try. Have a nice day!

Just fixing your regex:

[\w\s]+\n

you might need to play with \\n and \\ra bit. [\\w\\s] is equivalent to . so .*\\n will do the job as well

Yours didn't work as you stopped at first whitespace, while you want to replace any word or whitespace until the linefeed, as far as I can understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM