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'
A double-quoted string can have single quotes without escaping them, conversely, a single-quoted string can have double quotes within it without having to escape them. Double quotes ( \" ) must escape a double quote and vice versa single quotes ( \' ) must escape a single quote.
Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex. However, because Java uses double quotes to delimit String constants, if you want to create a string in Java with a double quote in it, you must escape them.
You do not need to backslash/escape the single quote.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
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)
Try something like this:
^[^"]*?('[^"]+?')[^"]*$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With