Mark
Mark

Reputation: 981

Minimum Length Regular Expression

I'm trying to write a regular expression that will validate that user input is greater than X number of non-whitespace characters. I'm basically trying to filter out begining and ending whitespace while still ensuring that the input is greater than X characters; the characters can be anything, just not whitespace (space, tab, return, newline). This the regex I've been using, but it doesn't work:

\s.{10}.*\s

I'm using C# 4.0 (Asp.net Regular Expression Validator) btw if that matters.

Upvotes: 7

Views: 13998

Answers (3)

Danny Fallas
Danny Fallas

Reputation: 628

If your trying to check (like in my case a phone number that contains 8 digits) , you need to refer to a number below the one you need.

(\s*(\S)\s*){7,}

Upvotes: 1

Michael Liu
Michael Liu

Reputation: 55529

This regular expression looks for eight or more characters between the first and last non-whitespace characters, ignoring leading and trailing whitespace:

\s*\S.{8,}\S\s*

Upvotes: 3

John Rasch
John Rasch

Reputation: 63505

It may be easier to not use regex at all:

input.Where(c => !char.IsWhiteSpace(c)).Count() > 10

If whitespace shouldn't count in the middle, then this will work:

(\s*(\S)\s*){10,}

If you don't care about whitespace in between non-whitespace characters, the other answers have that scenario covered.

Upvotes: 8

Related Questions