Reputation: 433
Why does the following code find nothing in C# but works fine when I tested it online?
Match m = Regex.Match(@"abc
cd", "^abc[ \t]*$", RegexOptions.Multiline);
I am using this online regular expressions tester: http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
I expect to get "abc"
Upvotes: 0
Views: 353
Reputation: 433
I think I know what's happening here. In my text file the EOL is CRLF. But the C# regex treats the LF as the EOL(which is the '$'). So in my case the regex cannot find the CR and claim a failure. And @"^abc[ \t\r]*$" works.
Upvotes: 0
Reputation: 11233
As I understood you haven't captured any group so you get nothing as a result.
First try this:
Debug.Print(Regex.IsMatch(@"abc
cd", "^abc[ \t]*$", RegexOptions.Multiline).ToString());
You should get true
, since there is a match.
Then try this: (notice the braces '()' after '^' and before '$')
Debug.Print(Regex.Match(@"abc
cd", "^(abc[ \t]*)$", RegexOptions.Multiline).ToString());
You should get a result in Output Window
.
Hope it helps!
Upvotes: 0
Reputation: 3188
If you want to get abc
you can use: ^abc.*$
instead.
If you want to get all,
you can use: (?s)^abc.*$
instead.
I think your issue is: [ \t] can not match newline, so you also can change your code to match new line like this:
Match m = Regex.Match(@"abc
cd", @"^abc[ \t\r]*$", RegexOptions.Multiline);
Upvotes: 1
Reputation: 32681
For a multiline string, you can remove the spaces at the end without using Regex.
string trimEnd = string.Join("\n", yourString.Split('\n').Select(x => x.TrimEnd()));
Upvotes: 1