C#正则表达式替换URL [英] C# Regex replace url

查看:281
本文介绍了C#正则表达式替换URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一大堆的这必须由JavaScript调用来代替一个文档中的链接。所有的链接看起来是一样的:

I have a bunch of links in a document which has to be replaced by a javascript call. All the links looks the same:

<a href="http://domain/ViewDocument.aspx?id=3D1&doc=form" target="_blank">Document naam 1</a>
<a href="http://domain/ViewDocument.aspx?id=3D2&doc=form" target="_blank">Document naam 2</a>
<a href="http://domain/ViewDocument.aspx?id=3D3&doc=form" target="_blank">Document naam 3</a>

现在我想所有这些链接被替换为:

Now I want all this links to be replaced to:

<a href="javascript:loadDocument('1','form')">Document naam 1</a>
<a href="javascript:loadDocument('2','form')">Document naam 2</a>
<a href="javascript:loadDocument('3','form')">Document naam 3</a>



所以说ID = 3D在URL中的函数的第一个参数和文档参数是在函数调用的第二个参数。

So the Id=3D in the url is the first parameter in the function and the doc parameter is the second parameter in the function call.

我想这样做,使用正则表达式,因为我觉得这是最快捷的方式。但问题是我的正则表达式的知识太有限

I want to do this using Regex because I think this is the quickest way. But the problem is my regex knowledge is too limited

推荐答案

Polygenelubricants 指出我的非常正确的方式,但删除的他的回答:(

Polygenelubricants has pointed me in the very right way, but has removed his answer :(

他给我这。链接多亏了他,我发现我的解决方案:

He gave me this link. Thanks to him I found my solution:

string replaced = "";

string regex = "<a href=3D\"http://\\S+id=3D(\\d+)&doc=3D(\\w+)\" target=3D\"_parent\">";
Regex regEx = new Regex(regex);

replaced = regEx.Replace(mhtFile, "<a href=3D\"javascript:window.parent.loadDocument('$1','$2')\">");

Response.Write(replaced);

对于那些谁感兴趣的话,这个链接是一个.mht文件中。这就是为什么3D是等号(=)之后。变量mhtFile包含纯文本MHT整个MHT文件。

For those who are interested, this links are inside a .mht file. That's why the 3D are placed after the = sign. The variable mhtFile contains the whole mht file in plain mht text.

这篇关于C#正则表达式替换URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆