Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .NET正则表达式问题_C#_Regex_Parsing - Fatal编程技术网

C# .NET正则表达式问题

C# .NET正则表达式问题,c#,regex,parsing,C#,Regex,Parsing,我正试图从网站上解析一些数据。问题是javascript生成数据,因此我不能使用HTML解析器。源中的字符串如下所示: <a href="http:www.domain.compid.php?id=123"> 一切都是常量,除了在=。我也不知道字符串会出现多少次。如果可能的话,请提供有关正则表达式示例的帮助和解释。是否需要保存其中的任何内容?一揽子正则表达式href=“[^”]+”>将匹配整个字符串。如果需要保存特定部分,请告诉我 编辑:要保存id,请注意id=后面的paren

我正试图从网站上解析一些数据。问题是javascript生成数据,因此我不能使用HTML解析器。源中的字符串如下所示:

<a href="http:www.domain.compid.php?id=123">


一切都是常量,除了在=。我也不知道字符串会出现多少次。如果可能的话,请提供有关正则表达式示例的帮助和解释。

是否需要保存其中的任何内容?一揽子正则表达式
href=“[^”]+”>
将匹配整个字符串。如果需要保存特定部分,请告诉我

编辑:要保存id,请注意
id=
后面的paren,这表示要捕获它。然后要检索它,请使用匹配对象的Groups字段

string source = "a href=\"http:www.domain.compid.php?id=123\">";
Regex re = new Regex("href=\"[^\"]+id=([^\"]+)\">");

Match match = re.Match(source);
if(match.Success)
{
    Console.WriteLine("It's a match!\nI found:{0}", match.Groups[0].Value);
    Console.WriteLine("And the id is {0}", match.Groups[1].Value);
}
编辑:使用
MatchCollection

MatchCollection mc = re.Matches(source);

foreach(Match m in mc)
{
    //do the same as above. except use "m" instead of "match"
    //though you don't have to check for success in each m match object 
    //since it wouldn't have been added to the MatchCollection if it wasn't a match
}

这将在javascript中进行解析并创建csv字符串:

var re = /<a href="http:www.domain.compid.php\?id=(\d+)">/;
var source = document.body.innerHTML;
var result = "result: ";

var match = re(source);
while (match != null) {
    result += match[1] + ",";
    source = source.substring(match.index + match[0].length);
    match = re(source);
}
var re=/。如果html内容不用于服务器上的任何其他内容,则足以发送ID

编辑,为了性能和可靠性,最好使用内置javascript函数(或jQuery)查找URL,而不是搜索整个内容:

var re = /www.domain.compid.php\?id=(\d+)/;
var as = document.getElementsByTagName('a');    
var result = "result: ";

for (var i = 0; i < as.length; i++) {
    var match = re(as[i].getAttribute('href'));
    if (match != null) {
        result += match[1] + ",";
    }
}
var re=/www.domain.compid.php\?id=(\d+)/;
var as=document.getElementsByTagName('a');
var result=“结果:”;
对于(变量i=0;i
如果可以将其传递给regex,为什么不能将其传递给适当的解析器?因为源代码被javascript unicode字符(如“\u003A”)所扭曲“而且HtmlAgilityPack也不能与javascript一起使用。@谢谢,看起来很棒。但是,我不确定应该如何使用该值作为模式,因为它里面有双引号。我想通过使用verbatim@string,但它没有编译(无效的表达式术语“)”,对于^@regexnewb,我用一个例子更新了我的答案。您需要通过执行
\“
@jb来转义正则表达式中的
,谢谢,这是可行的,是否可以只解析出id=?@regexnewb之后的值,当然可以,因此在这种情况下,您希望保存“123”,对吗?@jb谢谢,这适用于单个匹配。如果我使用MatchCollection,如何从中获取id?因为我有多个链接,我想我需要使用MatchCollection来“收集”它们。