RegEx: match a string enclosed in single quotes, but not matching those enclosed in double quotes

I wanted to write a regular expression to match strings enclosed in single quotes, but should not match a string with a single quotation mark enclosed in double quotation marks.

Example 1:

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

the whole value of a must match because it is enclosed in single quotes.

EDIT: The exact match should be: 'This is a one-line string

Example 2:

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

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

I tried /'.*'/g , but it also matches a single quote inside a double quote string.

!

EDIT:

:

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

:

'the lazy dog'
+4
3

, ( , ), ( It's... "Monty Python Flying Circus"!), :

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

regex101.com.

:

'        # 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)
+5

- :

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

Live Demo

+1

If you are not strictly limited to a regular expression, you can use the "indexOf" function to find out if it is a double quote string:

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 JSFiddle below:

Jsfiddle

0
source

Source: https://habr.com/ru/post/1533272/


All Articles