简体   繁体   English

RegEx模式不适用于AJAX响应

[英]RegEx Pattern Does Not Work With AJAX Response

UPDATED 更新

I need some help from you to defeat the regexp! 我需要您的帮助来击败正则表达式! I'm getting the external CSS file in a form of AJAX response like this: 我正在以如下形式的AJAX响应形式获取外部CSS文件:

$.when($.get("style.css")).done(function(response) {
    var myCSS = response;
    var patt = new RegExp("#mydiv(.*?)}","g");
    var match = myCSS.match(patt);
    alert(match);  
}

What I'm trying to achieve here is I want to get everything from #mydiv to the last closing bracket } , but for some reason alert(match) returns me null . 我想要在这里实现的是,我想要获取从#mydiv到最后一个括号}的所有内容 ,但是由于某种原因, alert(match)使我返回null

The most annoying thing is when I change the pattern to: 最烦人的是,当我将模式更改为:

var patt = new RegExp("#mydiv(.*?){","g"); // <-- Changed } to {

alert(match) returns me what is supposed to be returned --> #mydiv .mylink { alert(match)返回我应该返回的内容-> #mydiv .mylink {

Or when I represent the same CSS in a form of a simple string like this: 或者,当我以简单的字符串形式表示相同的CSS时,如下所示:

$.when($.get("style.css")).done(function(response) {
    var myCSS = "The same style.css but copy-pasted here";
    var patt = new RegExp("#mydiv(.*?)}","g");
    var match = myCSS.match(patt);
    alert(match);  
}

Works with my initial pattern as expected. 按预期与我的初始模式兼容。 Any thoughts what am I missing here? 有什么想法我在这里想念吗?

The } is a reserved character on regex, you have to escape it with \\ . }是正则表达式上的保留字符,您必须使用\\对其进行转义。 I think regex you're after is "#mydiv(.*)\\}" or "#mydiv(.*)\\\\}" if the \\ itself has to be escaped. 我认为,如果必须自己转义\\ "#mydiv(.*)\\}"正则表达式是"#mydiv(.*)\\}""#mydiv(.*)\\\\}"

Ok I think I've found the solution. 好吧,我想我已经找到了解决方案。

var patt = new RegExp("#" + myID + "(\n|.)*?}","g");

After crazy googling, stackoverflowing and discussing with the community all night long. 经过疯狂的谷歌搜索后,整个晚上都出现堆栈溢出并与社区进行讨论。 I've found that the problem is that JS Regex does not recognize the . 我发现问题是JS Regex无法识别. as a new line so you need to put (\\n|.) instead. 作为新行,因此您需要放入(\\n|.)

I'm not sure that this solution is universal, and will ty to test it on different CSS files. 我不确定该解决方案是否通用,是否愿意在其他CSS文件上进行测试。 Thank you guys that commented my post! 谢谢那些评论我的帖子! I really appreciate your collaboration! 非常感谢您的合作!

Source: the very end of http://goo.gl/1W55l 来源: http //goo.gl/1W55l的结尾

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

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