0

Issue


I am having an issue creating a regex to accept any string and the ENTER key, at the moment i have this:

^$|^.+$

I have looked around and people have said to add \n but this does not work.

An example of the string is should allow is as follows:

Hello this is a test string


and i want this to be accepted
Ben Clarke
  • 949
  • 3
  • 17
  • 39
  • 2
    It seems you need `(?s)^.*$`. However, what good is this regex that matches all, incl. empty, strings? Could you please precise the requirements? – Wiktor Stribiżew Jul 11 '16 at 14:32
  • 1
    `\n` is **not** "the enter key", it's a **Line Feed** – Manfred Radlwimmer Jul 11 '16 at 14:34
  • Why do you need regex? More specifically, what are you trying to do that requires you to receive an enter key in a string using regex? Is it a console based app? You tagged the question c#, but there's no c# code or anything that relates to c# here. More to the point: are you looking for new lines in a string (that is, the enter key's representation in a series of characters), or to accept a string as input? – Richard Barker Jul 11 '16 at 14:37
  • @WiktorStribiżew Basically its a C# windows service application where we want to handle validation through an engine in SQL. We are then able to change the Validation as we wish without doing a an update to the product. In a few weeks we will be tightening the validation on some things but for now we have it in place. – Ben Clarke Jul 11 '16 at 14:42
  • 1
    So, is it just a matter of adding `RegexOptions.Singleline` flag to your regex? Like `new Regex(@"^.*$", RegexOptions.Singleline)`? – Wiktor Stribiżew Jul 11 '16 at 14:44

2 Answers2

2

Try setting the s flag on the regex engine. This will ensure that the . metacharacter will match newlines.

Here's a link to a working example.

Also, as a sidenote, instead of ^$|^.+$ you can condense the whole expression to ^.*$ to achieve the same results with better performance.


wpcarro
  • 1,473
  • 9
  • 11
  • s is whitespace, not multiline – deltree Jul 11 '16 at 14:38
  • `\s` is whitespace. The `m` flag is multiline, but that's not what I'm referencing. The `s` flag is single-line mode, making `.` match newline characters. View the example if you're confused about the distinctions. – wpcarro Jul 11 '16 at 14:39
1

In C#, you need the RegexOptions.Singleline option. See this SO post for more information.

Here is a quick example that really just matches the entire string, so it's not useful.

var regex = new Regex(@"^.*$",
              RegexOptions.IgnoreCase | RegexOptions.Singleline);

In your future validation code, you need to replace .* with whatever your validation will be.

Frank Bryce
  • 6,871
  • 3
  • 31
  • 51