我正在尝试使用JavaScript解析字符串。字符串要么用引号引起来,要么为单个Apply filter
字符。
示例:
=
我发现以下仅用于第一种情况的RegEx模式–至少当我在RegExr上使用它时,它不适用于JavaScript:"String 1" "String 2" "String 3"
"String 1" = "String 3"
"String 1" "String 2" =
"String 1" = =
示例:
(["'])(?:(?=(\\?))\2.)*?\1
如何将这种模式转换为可在JavaScript中使用,如何将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]
添加到模式中?
答案 0 :(得分:1)
假设您不关心转义的引号(例如"a\"b"
),那么此正则表达式将匹配带引号的字符串或等号:"[^"]*"|'[^"]*'|=
。您可以将其用作:
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\""
]