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

Answers


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


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,}$/

Need Your Help

Java Web App Security using Cookies

java security http cookies

I'm finishing a Cattle Drive assignment where a small Java web application manages a movie library for the client. The assignment is to put some security on the application using cookies, so that a

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.