Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce a single line using Regex?

I need a Regex object that will reject any string that spreads across multiple lines.

I want this to succeed:

"This is my string"

And this to fail:

"This is my string" + Environment.NewLine + "that spreads acrosss" + Environment.NewLine + "multiple lines."

I have been reading on the documentation on MSDN and assumed the following should work:

  • Regular expression pattern: "^.+"
  • Regex object initialized with this pattern, WITHOUT any options (no RegexOptions.Singleline or RegexOptions.Multiline).

When testing with multiple line strings, the Regex.IsMatch method always return true. I believe it is because IsMatch will return true when there is at least a portion of the string that matches the pattern.

In my case, anything prior to a new line will cause a match. The only way this will fail is if the string only has line breaks and no other char.

Is there a Regex validation method that will consider the string as a whole, instead of splitting it in matching sub-strings? I suspect I probably need a more complex string pattern to achieve my goal.

like image 226
Louis Avatar asked Oct 23 '25 04:10

Louis


1 Answers

You can use this regex to match only single line:

^[^\r\n]+$

And you need not use RegexOptions.Multiline with this regex.

like image 114
anubhava Avatar answered Oct 25 '25 17:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!