Reputation: 4337
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.
Upvotes: 2
Views: 70
Reputation: 3215
Just fixing your regex:
[\w\s]+\n
you might need to play with \n and \r a 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.
Upvotes: 0
Reputation: 11228
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;
Upvotes: 1
Reputation: 237
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!
Upvotes: 0
Reputation: 626861
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
Upvotes: 3