user1052591
user1052591

Reputation: 185

Regex not working as expected

Whats wrong with this regular expression?

/^[a-zA-Z\d\s&#-\('"]{1,7}$/; 

when I enter the following valid input, it fails:

a&'-#"2

Also check for 2 consecutive spaces within the input.

Upvotes: 2

Views: 113

Answers (5)

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

The dash needs to be either escaped (\-) or placed at the end of the character class, or it will signify a range (as in A-Z), not a literal dash:

/^[A-Z\d\s&#('"-]{1,7}$/i

would be a better regex.

N. B: [#-\(] would have matched #, $, %, &, ' or (.

To address the added requirement of not allowing two consecutive spaces, use a lookahead assertion:

/^(?!.*\s{2})[A-Z\d\s&#('"-]{1,7}$/i

(?!.*\s{2}) means "Assert that it's impossible to match (from the current position) any string followed by two whitespace characters". One caveat: The dot doesn't match newline characters.

Upvotes: 5

MatthiasC
MatthiasC

Reputation: 344

Your input does not match the regular expression. The problem here is the hyphen in you regexp. If you move it from its position after the '#' character to the start of the regex, like so:

/^[-a-zA-Z\d\s&#\('"]{1,7}$/;

everything is fine and dandy.

You can always use Rubular for checking your regular expressions. I use it on a regular (no pun intended) basis.

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148744

remove the ; at the end and

^[a-zA-Z\d\s\&\#\-\(\'\"]+$

Upvotes: 0

CanSpice
CanSpice

Reputation: 35828

You have an unescaped - in the middle of your character class. This means that you're actually searching for all characters between and including # and ( (which are #, $, %, &, ', and (). Either move it to the end or escape it with a backslash. Your regex should read:

/^[a-zA-Z\d\s&#\('"-]{1,7}$/

or

/^[a-zA-Z\d\s&#\-\('"]{1,7}$/

Upvotes: 1

FatalError
FatalError

Reputation: 54631

The - (hyphen) has a special meaning inside a character class, used for specifying ranges. Did you mean to escape it?:

/^[a-zA-Z\d\s&#\-\('"]{1,7}$/;

This RegExp matches your input.

Upvotes: 1

Related Questions