Darren
Darren

Reputation: 189

.Net Multiline Regex expression to restrict to integers

I am having a problem with a very simple regular expression.

I want to restrict the entry in a multi-line TextBox to just integers. The regular expression I have works fine in single line mode (for a single line TextBox, not using multiline option), but allows alpha characters to creep in when in multiline mode, but only once a new line has been entered.

My code (C#) is something like:

Regex regExpr = new Regex("^(\d*)$", RegexOptions.Multiline)
return regExpr.IsMatch(testString);

I want the following examples to be valid:

1

1\\n

1\\n2\\n3

I want the following to be invalid

A

A1\\n2

1\\n2\\nA3

Thanks in advance.

Upvotes: 4

Views: 534

Answers (3)

Andrew
Andrew

Reputation: 1357

You can match digits and newlines with:

Regex regExpr = new Regex("[\d\n]*", RegexOptions.Multiline)

This will match any number of digits and newlines. If you just want to make sure that the entered text doesn't have a NON digit, then use

Regex regExpr = new Regex("[\D\S]", RegexOptions.Multiline)

and if it matches, then you have an illegal entry.

Upvotes: 1

Nicolas
Nicolas

Reputation: 6494

What about

(\d?\\n*)?

Upvotes: 0

Keng
Keng

Reputation: 53101

Do you want to destructively remove the alphas or just send it back for the user to re-enter the info?

to remove just do a search replace with with an empty result.

[^\d\n]

To check to see if there's anything other than a number and \n do the same thing only on the first occurrence error the page submit and send back to the user.

Since I don't know which .Net lang you're using I can only give general principles.

Upvotes: 0

Related Questions