Javascript 正则表达式报价

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6520407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:56:35  来源:igfitidea点击:

Javascript RegEx quote

javascriptregex

提问by cnotethegr8

I'm having trouble getting this Javascript Regular Expression to work. What i want is to find a character that starts with @"has any characters in the middle and ends with ". I will also need it in a single quote from.

我无法让这个 Javascript 正则表达式工作。我想要的是找到一个以 开头的@"字符,中间有任何字符,以". 我还需要它在单引号中。

The tricky part for me, is that it cant be starting with @"and ending with "because the string it's looking through could look like [UIImage imageNamed:@"glass-round-red-green-button.png"].

对我来说棘手的部分是它不能以开头@"和结尾,"因为它正在查看的字符串可能看起来像[UIImage imageNamed:@"glass-round-red-green-button.png"].

So far what i have is this.

到目前为止,我所拥有的是这个。

regex: new RegExp('\\@"?\\w+\\b"*', 'g')

regex: new RegExp('\\@"?\\w+\\b"*', 'g')

回答by Gumbo

Try this regular expression:

试试这个正则表达式:

/@(["'])[^]*?/g

An explanation:

一个解释:

  • @(["'])matches either @"or @'
  • [^]*?matches any arbitrary character ([^]contains all characters in opposite to .that doesn't contain line-breaks), but in a non-greedy manner
  • \1matches the same character as matches with (["'])
  • @(["'])匹配@"@'
  • [^]*?匹配任何任意字符([^]包含与.不包含换行符相反的所有字符),但以非贪婪的方式
  • \1匹配与匹配相同的字符 (["'])

Using the literal RegExp syntax /…/is more convenient. Note that this doesn't escape sequences like \"into account.

使用文字 RegExp 语法/…/更方便。请注意,这不会像\"考虑一样转义序列。

回答by Qtax

The regex would be: var regex = /@"[^"]*"/g;

正则表达式将是: var regex = /@"[^"]*"/g;

回答by Hyman Giffin

Gumbo's regexp is very nice and all, however it fails to detect escaped quotes (e.g. \", \\\", etc.). A regexp that solves this is as follows:

浓汤的正则表达式是非常好的,所有的,但它不能检测转义引号(例如\"\\\"等)。解决这个问题的正则表达式如下:

/@(["'])[^]*?[^\](?:\\)*|@""|@''/g

An explanation (continuing from Gumbo's explanation):

一个解释(接续 Gumbo 的解释):

  • [^\\]matches the nearest character preccedding the ending quote that is not a backslash (to anchor the back-slash count check).
  • (?:\\\\)*matches only if the number of backslashes is a multiple of 2 (including zero) so that escaped backslashes are not counted.
  • |@""checks to see if there is an empty double quote because [^\\]requires at least one character present in the string for it to work.
  • |@''checks to see if there is an empty single quote.
  • [^\\]匹配不是反斜杠的结束引号之前的最近字符(以锚定反斜杠计数检查)。
  • (?:\\\\)*仅当反斜杠的数量是 2 的倍数(包括零)时才匹配,以便不计算转义的反斜杠。
  • |@""检查是否有空双引号,因为[^\\]字符串中至少需要一个字符才能工作。
  • |@''检查是否有空单引号。