简体   繁体   English

无效的正则表达式Javascript

[英]Invalid Regular Expression` Javascript

I'm trying to parse CSS file with this expression: 我正在尝试使用以下表达式解析CSS文件:

rulePatt = new RegExp("(?<=\\s)(?<!\\:\\s)#.*?\\{.*?\\}","gm");

It works in two different regex testers I used, but when I put it in the wild it generates javascript error: 它可以在我使用的两个不同的正则表达式测试器中工作,但是当我将其放到野外时会生成javascript错误:

Uncaught SyntaxError: Invalid regular expression: /(?<=\s)(?<!\:\s)#.*?\{.*?\}/: Invalid group

Fiddle here to form a impression on what I'm trying to achieve: http://jsfiddle.net/LoomyBear/44XtU/1/ 小提琴在这里对我要实现的目标印象深刻: http : //jsfiddle.net/LoomyBear/44XtU/1/

I guess I miss something really important here. 我想我在这里错过了一些非常重要的事情。 Please help ... Thanks! 请帮忙...谢谢!

You can use this pattern 您可以使用此模式

var regex = /(?:^|[^:])\s(#[^{]*\{[^}]*\})/gm;

Your result is in the first capturing group. 您的结果在第一个捕获组中。

explanations: 解释:

(?:^|[^:])   # begining of the line or a character that is not a :
\s           # a white space
(#
[^{]*        # all characters expect { zero or more times
\{
[^}]*        # all characters expect } zero or more times
\})

The first lookbehind (?<=\\s) imposes a white space before the sharp, it s the reason why i wrote a \\s before. 后面的第一个(?<=\\s)在尖锐字符前加一个空格,这就是我之前写一个\\ s的原因。 The second lookbehind (?<!:\\s) forbids a : before this space, thus, at this position is only allowed nothing (ie: the begining of the line) or a character that is not a : 在此空格后面的第二个后视(?<!:\\s)禁止在此空格之前使用: ,因此,在此位置只允许不输入任何内容(即:该行的开头)或一个不是的字符:

You can mimic look-behinds in JavaScript by using memory groups, eg: 您可以通过使用内存组来模仿JavaScript中的回溯,例如:

var patt1 = /(?:\}|$)\s*(#[^\{]+)/g,
    m;

while ((m = patt1.exec(parseStr)) !== null) {
    output += m[1] + '<br>';
}

Demo 演示

First you match either the start of the subject or the closing brace of the previous definition, followed by optional white space. 首先,您匹配主题的开头或上一个定义的右括号,然后是可选的空白。 The rest is more or less your original expression. 其余部分或多或少是您的原始表达方式。

To iterate over each match you must use RegExp.exec() instead of $.each() so that you can choose which memory group to add to output . 要遍历每个匹配项,必须使用RegExp.exec()而不是$.each()以便可以选择要添加到output内存组。

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

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