Billy Lei
Billy Lei

Reputation: 31

REGEX for maximum 1 space between character ,no leading or trailing space

I have regex which should match following

  1. No leading or trailing space

  2. {A-Z0-0}

  3. Allow only maximum 1 space in between word

  4. Total including space is 35 character

For example

(no space)ABC 123 450(no space) <-- Pass
(space)ABC 123 450(no space) <--Fail
(no space)ABC(space)(space)EFG(no space) <--Fail

I have try ^\S{0,35}(?: \S+){0,35}$ but I am still not able to get rid of the leading space Thanks``

Upvotes: 2

Views: 602

Answers (2)

Richard
Richard

Reputation: 109015

Assuming you have a sufficiently powerful regex engine, use a zero width look-ahead to check the total length (using \w here as a proxy for [0-9a-zA-Z] to make it easier to read here despite that including some unwanted characters):

^(?=.{1,35}$)((\w+ )*?\w+$)

Explanation

^            Match the start
(?=.{1,35}$) At this point, there are between 1 and 35 characters before the end
(\w+ )*?     Match zero or more (preferring less) repetitions of
             one or more alphanumerics followed by a single space
\w+          Match one or more alphanumerics
$            End of the string

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521389

Try this pattern:

^(?!.*[ ]{2,})(?:\S[A-Z0-9 ]{0,33}\S)?$

As for an explanation, the (?!.*[ ]{2,}) term is a negative lookahead, which asserts that the input does not contain two or more continuous spaces anywhere. Then, the (?:\S[A-Z0-9 ]{0,34})? term matches a non space character, followed by 0 to 33 uppers or numbers, followed by another non space. This covers a single character or more. To cover the case of an empty input matching, we make this entire term optional using ?.

Demo

Upvotes: 0

Related Questions