-1

我有这段文字:

    <script type="text/javascript" id="wordpress_grazit_script">        
            var dbnurls = [];
            var dbnanchors = [];
            dbnurls.push('url');
            dbnanchors.push('anchor');
            var script = document.createElement("script");
            script.setAttribute("src", dbn_protocol+"path to js");
            script.setAttribute("type", "text/javascript");
            script.setAttribute("id", "grazit_script");
            document.getElementById("my-id").parentNode.appendChild(script);
    </script>

我需要用其他东西替换 dbn_protocol+"path to js"。

我尝试使用这种匹配模式,但它一直匹配到最后一个);

    "script\\.setAttribute\\([\"']src[\"'],(.*[^\\);])(\\);)(.*)"

我需要在 c# .net 中指定我需要这个正则表达式

谢谢

4

4 回答 4

1

您只能匹配 from dbn_protocol(并在定义正则表达式时使用@符号,因此您不必进行一堆双重转义):

var regex = new Regex(@"dbn_protocol\+""[^""]+""");

理想的例子

使用引号将阻止正则表达式匹配超过path to js.

于 2013-08-30T19:30:44.670 回答
0

如果你只想替换dbn_protocol+"path to js",有几种方法可以实现,首先你可以直接用新的东西替换dbn_protocol+"path to js"使用

string.Replace(string searchterm,string replacementterm);

但是正如你提到的你想要正则表达式中的东西,所以试试下面的方法,它返回一个新字符串(这是一个新的脚本部分,替换了dbn_protocol+“js 路径”)。这应该会让你满意,因为它是使用正则表达式完成的;

Regex r = new Regex(@"dbn_protocol\+""[^""]+""");
string newscript=r.Replace("your script's text","the replacement string");
//newscript is the script text that you need.

如果您需要绝对更改一次,我还想指出一件事,那么为什么您选择在代码中进行,而您可以轻松地手动完成。

希望它有效。

于 2013-08-30T19:45:12.290 回答
0

谢谢克里斯的回答。问题是你说的。正则表达式很贪心,一直到最后一场比赛。我把'?这一切都奏效了。

谢谢

于 2013-09-02T06:05:59.477 回答
0

如果在javascript中你可以这样做:

var result = yourScriptString.replace(
    /(script\.setAttribute\("src",)(.*)(\))/, 
    " $1'" + someUrl + "'$3");

有关详细信息,请参阅此 jsfiddle

于 2013-08-30T13:26:25.967 回答