简体   繁体   中英

Find strings enclosed in quotes and equal-signs using RegEx

I'm trying to parse strings using JavaScript. The strings are either enclosed in quotes or are a single = character.

Examples:

"String 1" "String 2" "String 3"
"String 1" = "String 3"
"String 1" "String 2" =
"String 1" = =

I've discovered the following RegEx pattern that covers the first case only – at least when I use it on RegExr , it does not work in JavaScript: (["'])(?:(?=(\\\\?))\\2.)*?\\1

Example:

const re = /(["'])(?:(?=(\\?))\2.)*?\1/;
const str = '"String 1" "String 2" "String 3"';

re.exec(str);

//=> [""String 1"", """, "", index: 0, input: ""String 1" "String 2" "String 3"", groups: undefined]

How can I translate this pattern to work in JavaScript and how can I add the = to the pattern?

Assuming you're not concerned with escaped quotations marks (eg "a\\"b" ), then this regex will match quoted strings or equal signs: "[^"]*"|'[^"]*'|= . You could use it as:

 let input = `"String 1" "String 2" 'String 3' = = "string 4"`; let matches = input.match(/"[^"]*"|'[^"]*'|=/g); console.log(matches); [ "\\"String 1\\"", "\\"String 2\\"", "'String 3'", "=", "=", "\\"string 4\\"" ] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM