Nick White
Nick White

Reputation: 1612

Regex to not match when not in quotes

I'm looking to create a JS Regex that matches double spaces

([-!$%^&*()_+|~=`{}\[\]:";'<>?,.\w\/]\s\s[^\s])

The RegEx should match double spaces (not including the start or end of a line, when wrapped within quotes).

Any help on this would be greatly appreciated.

For example:

var x = 1,
    Y = 2;

Would be fine where as

var x =  1;

would not (more than one space after the = sign.

Also if it was

console.log("I am some console  output");

would be fine as it is within double quotes

Upvotes: 0

Views: 688

Answers (2)

zx81
zx81

Reputation: 41838

This problem is a classic case of the technique explained in this question to "regex-match a pattern, excluding..."

We can solve it with a beautifully-simple regex:

(["'])  \1|([ ]{2})

The left side of the alternation | matches complete ' ' and " ". We will ignore these matches. The right side matches and captures double spaces to Group 2, and we know they are the right ones because they were not matched by the expression on the left.

This program shows how to use the regex in JavaScript, where we will retrieve the Group 2 captures:

var the_captures = []; 
var string = 'your_test_string'
var myregex = /(["'])  \1|([ ]{2})/g;
var thematch = myregex.exec(string);
while (thematch != null) {
    // add it to array of captures
    the_captures.push(thematch[2]);
    document.write(thematch[2],"<br />");    
    // match the next one
    thematch = myregex.exec(string);
}

A Neat Variation for Perl and PCRE

In the original answer, I hadn't noticed that this was a JavaScript question (the tag was added later), so I had given this solution:

(["'])  \1(*SKIP)(*FAIL)|[ ]{2} 

Here, thanks to (*SKIP)(*FAIL) magic, we can directly match the spaces, without capture groups.

See demo.

Reference

Upvotes: 4

user2576899
user2576899

Reputation: 11

Simple solution:

/\s{2,}/

This matches all occurrences of one or more whitespace characters. If you need to match the entire line, but only if it contains two or more consecutive whitespace characters:

/^.*\s{2,}.*$/

If the whitespaces don't need to be consecutive:

/^(.*\s.*){2,}$/

Upvotes: -1

Related Questions