简体   繁体   English

使用正则表达式获取子字符串(带有“”的字符串)

[英]Getting substrings (strings with “”) with Regex

I have a main string like this:我有一个这样的主字符串:

const mainString: string = `
let myStr: string = "Hello world";
function x() { }
let otherVar: number = 4;
let otherString: string = "Other string value";
// something else INSIDE the main string
`;

Now I need to format this main string, but substrings cause unwanted stuff, so I need to get them.现在我需要格式化这个主字符串,但是子字符串会导致不需要的东西,所以我需要得到它们。

The regex I used until now was: /"([^"]*)"/g . With it I would get eg ['"Hello world"', '"Other string value"'] (in the mainString context from above).直到现在我使用的正则表达式是: /"([^"]*)"/g 。有了它,我会得到例如['"Hello world"', '"Other string value"'] (在上面的 mainString 上下文中)。

But having a "\\"" inside one of these substring, would throw off my regex and give me the part from the beginning until the \\" and then, if some other substring was used anywhere else, give me the real end of the substring " (falsly as a start symbol) until the start of the next substring...但是在这些子字符串之一中有一个"\\"" ,会抛弃我的正则表达式并给我从开始到\\" ,然后,如果在其他任何地方使用了其他一些子字符串,给我子字符串的真正结尾" (错误地作为开始符号)直到下一个子串的开始......

One important thing: I have absolutly no control what so ever about anything before and beyont the "substring value" .一件重要的事情:我完全无法控制之前和超出"substring value"任何事情。

What would be the correct regex for my usecase?我的用例的正确正则表达式是什么?

Try this one试试这个

"((\\"|[^"])*?)"

\\\\" - mean look for \\" \\\\" - 表示寻找\\"

| - or - 或者

*? - for no greedy - 不贪心

see: regex101参见: regex101

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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