我有一个邮件收发器,我在其中发送一个html页面作为邮件正文。 html页面具有一些链接。我在这里所做的是识别这些链接,并将这些链接替换为指向我页面的链接,并将该链接作为查询字符串中的参数以及我在文本框中输入的参数“用户名”发送出去。这是代码-
StreamReader reader = new StreamReader(Server.MapPath("~/one.html"));
string readFile = reader.ReadToEnd();
Regex regx = new Regex("(?<!src=\")http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
string output = regx.ToString();
output = readFile;
string username = Server.UrlEncode(this.txtUsername.Text);
output = regx.Replace(output, new MatchEvaluator((match) =>
{
var url = Uri.EscapeDataString(match.Value.ToString());
return $"http://localhost:61187/two?sender={username}&link={url}";
}));
该URL中有一个产品代码。我想要的是产品代码以及链接。链接可以是-http://example.in/next/pr-01.html pr-01是产品代码。产品代码的格式为pr-01,pr-02 .... 我是.net的新手,并且之前没有使用过regex,所以我不知道如何分别获取产品代码和完整链接,并将其传递给查询字符串,如上所示
答案 0 :(得分:1)
尝试一下
Regex myRegex = new Regex(@"pr-.*([\d])");
答案 1 :(得分:0)
尽管可以使用正则表达式,但也可以不使用(这样做可能会提高性能)。
在这里,最后一个片段的下面是网址(pr-01.html
),
然后仅将其一部分放在文件扩展名(.html
)之前,并以.
开头,
产品代码为pr-01
。
String url = "http://example.in/next/pr-01.html";
Uri uri = new Uri(url, UriKind.Absolute);
String fileName = uri.Segments[uri.Segments.Length - 1]; // pr-01.html
String productCode = fileName.Substring(0, fileName.IndexOf(".")); // pr-01
编辑
上面的解析例程可以与您的代码结合,如下所示。
最后一行显示如何将产品代码包含在查询字符串中(您可能必须使用其他查询字符串参数名称)。
StreamReader reader = new StreamReader(Server.MapPath("~/one.html"));
string readFile = reader.ReadToEnd();
Regex regx = new Regex("(?<!src=\")http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
string output = regx.ToString();
output = readFile;
string username = Server.UrlEncode(this.txtUsername.Text);
output = regx.Replace(output, new MatchEvaluator((match) =>
{
Uri uri = new Uri(match.Value, UriKind.Absolute);
String fileName = uri.Segments[uri.Segments.Length - 1]; // pr-01.html
String productCode = Uri.EscapeDataString(fileName.Substring(0, fileName.IndexOf("."))); // pr-01
var url = Uri.EscapeDataString(match.Value.ToString());
return $"http://localhost:61187/two?sender={username}&link={url}&productcode={productCode}"; // << Include the productcode in the querystring.
}));