我已经继承了网站的代码,并且在提供部件号后,此特定功能用于从网站获取描述。我以前从未使用过正则表达式,因此该设置有点超出我的领域,并希望获得一些帮助来弄清楚为什么它不能正常工作。
基本上,此功能的理想操作是,当站点的用户在适当的字段中输入零件编号并按下按钮时,将从单独的站点获取的标准零件描述输出给用户。我检查了正则表达式试图匹配的第三方站点上的元素,并将其编码为
<span id="ctl00_BodyContentPlaceHolder_lblDescription">Random Description</span>
public static string GetPartHpDescription(string url)
{
// Create a request to the url
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
// If the request wasn't an HTTP request (like a file), ignore it
if (request == null) return null;
// Use the user's credentials
request.UseDefaultCredentials = true;
// Obtain a response from the server, if there was an error, return nothing
HttpWebResponse response = null;
try { response = request.GetResponse() as HttpWebResponse; }
catch (WebException) { return null; }
// Regular expression for an HTML title
// string regex = @"(?<=<body.*>)([Description : HP]*)(?=</body>)";
string regex = "<span [^>]*id=(\"|')ctl00_BodyContentPlaceHolder_lblDescription(\"|')>(.*?)</span>";
string regex1 = "<span [^>]*id=(\"|')ctl00_BodyContentPlaceHolder_gvGeneral_ctl02_lblpartdesc1(\"|')>(.*?)</span>";
// Regex re = new Regex(@"<span\s+id=""ctl00_BodyContentPlaceHolder_lblDescription");
// string regex = @"<span\s+id=""ctl00_BodyContentPlaceHolder_lblDescription"
// If the correct HTML header exists for HTML text, continue
if (new List<string>(response.Headers.AllKeys).Contains("Content-Type"))
if (response.Headers["Content-Type"].StartsWith("text/html"))
{
// Download the page
WebClient web = new WebClient();
web.UseDefaultCredentials = true;
string page = web.DownloadString(url);
// string title = Regex.Match(page, @"<span\s+id=""ctl00_BodyContentPlaceHolder_lblDescription"">.*?</span>", RegexOptions.IgnoreCase).Groups["Title"].Value;
// Extract the title
Regex ex = new Regex(regex, RegexOptions.IgnoreCase);
String data = ex.Match(page).Value.Trim();
if (data == "")
{
Regex ex1 = new Regex(regex1, RegexOptions.IgnoreCase);
data = ex1.Match(page).Value.Trim();
}
return data;
// return title;
}
// Not a valid HTML page
return null;
}
当前发生的情况是,如果部件号当前不在系统数据库(sql后端)中,则该功能无法正确获取部件说明。
答案 0 :(得分:0)
我的猜测是,我们有一些ID希望提取其textContnet,如果必须使用正则表达式,则可以从一个简单的表达式开始,然后在必要时添加更多约束,>
<span id=["'](ctl00_.+|other_ids)["']>(.+?)<\/span>
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"<span id=[""'](ctl00_.+|other_ids)[""']>(.+?)<\/span>";
string input = @"<span id=""ctl00_BodyContentPlaceHolder_lblDescription"">Random Description</span>
<span id='ctl00_BodyContentPlaceHolder_lblDescription'>Random Description</span>
";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
jex.im可视化正则表达式: