Claire
Claire

Reputation: 21

How to avoid spaces in my regular expression Regex?

this is my current regex.

^\s*(?:\S\s*){3,15}$

an example of the type of thing/format we are trying to capture correctly is:

(15 characters) ABCDFG001GRN-GH (but can be 16)

The above works fine as the majority of things are 15 characters.. but we have a few that are 16 characters and if we increase the 15 to 16 in the regex, we are worried we will capture spaces at the end of the 15 ones.. and want to be rejecting any 15 character entries with a space at the beginning or end..

Any ideas please?

Upvotes: 0

Views: 404

Answers (2)

The fourth bird
The fourth bird

Reputation: 163642

Using \s matches a whitespace char, \S matches a non whitspace char (can also match a newline).

Your pattern ^\s*(?:\S\s*){3,15}$ starts by matching optional whitespace chars, and ends with optional whitespace chars.

That pattern might also match:

ABCDFG001GRN-GH


If you want to match either 3-15 or 3-16 chars and:

rejecting any 15 character entries with a space at the beginning or end

you can start and end the pattern with a non whitspace char.

^\S(?:\s*\S){2,15}$

The pattern matches:

  • ^ Start of string
  • \S Match a single non whitespace char
  • (?:\s*\S){2,15} Repeat 2-15 times optional whitespace chars and a single non whitespace char
  • $ End of string

Regex demo

Upvotes: 0

Andy A.
Andy A.

Reputation: 1452

This is your current regex: current

As you can see, after every "NonWhiteSpace" may be a "Whitespace". So your current regex matches "A B C D E "! Thats not what you want.

Use /^s*\w{3,16}\s*$\ or /^\s*[A-Za-z0-9-]{3,16}\s*$/.

new1

new2

Images by jex.im.

See also:

Upvotes: 1

Related Questions