s4m0k
s4m0k

Reputation: 568

RegEx : Match a string enclosed in single quotes but don't match those inside double quotes

I wanted to write a regex to match the strings enclosed in single quotes but should not match a string with single quote that is enclosed in a double quote.

Example 1:

a = 'This is a single-quoted string';

the whole value of a should match because it is enclosed with single quotes.

EDIT: Exact match should be: 'This is a single-quoted string'

Example 2:

x = "This is a 'String' with single quote";

x should not return any match because the single quotes are found inside double quotes.

I have tried /'.*'/g but it also matches the single quoted string inside a double quoted string.

Thanks for the help!

EDIT:

To make it clearer

Given the below strings:

The "quick 'brown' fox" jumps
over 'the lazy dog' near
"the 'riverbank'".

The match should only be:

'the lazy dog'

Upvotes: 6

Views: 15622

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

Assuming that won't have to deal with escaped quotes (which would be possible but make the regex complicated), and that all quotes are correctly balanced (nothing like It's... "Monty Python's Flying Circus"!), then you could look for single-quoted strings that are followed by an even number of double quotes:

/'[^'"]*'(?=(?:[^"]*"[^"]*")*[^"]*$)/g

See it live on regex101.com.

Explanation:

'        # Match a '
[^'"]*   # Match any number of characters except ' or "
'        # Match a '
(?=      # Assert that the following regex could match here:
 (?:     # Start of non-capturing group:
  [^"]*" # Any number of non-double quotes, then a quote.
  [^"]*" # The same thing again, ensuring an even number of quotes.
 )*      # Match this group any number of times, including zero.
 [^"]*   # Then match any number of characters except "
 $       # until the end of the string.
)        # (End of lookahead assertion)

Upvotes: 8

NeverHopeless
NeverHopeless

Reputation: 11233

Try something like this:

^[^"]*?('[^"]+?')[^"]*$

Live Demo

Upvotes: 1

Kyo
Kyo

Reputation: 964

If you are not strictly bounded by the regex, you could use the function "indexOf" to find out if it's a substring of the double quoted match:

var a = "'This is a single-quoted string'";
var x = "\"This is a 'String' with single quote\"";

singlequoteonly(x);

function singlequoteonly(line){
    var single, double = "";
    if ( line.match(/\'(.+)\'/) != null ){
        single = line.match(/\'(.+)\'/)[1];
    }
    if( line.match(/\"(.+)\"/) != null ){
        double = line.match(/\"(.+)\"/)[1];
    }

    if( double.indexOf(single) == -1 ){
        alert(single + " is safe");
    }else{
        alert("Warning: Match [ " + single + " ] is in Line: [ " + double + " ]");
    }
}

See the JSFiddle below:

JSFiddle

Upvotes: 0

Related Questions