.Net Regex从文本中提取url永远不会返回

时间:2022-09-13 11:06:12

I have a .Net Regex expression that extracts all valid looking Urls from a string. It passes all 20 of my unit tests except one: when the Url contains a questionmark. This causes the Regex engine to hang the process and wreak havoc.

我有一个。net Regex表达式,它从字符串中提取所有有效的url。它通过了我所有的20个单元测试,除了一个:当Url包含一个问号时。这导致Regex引擎挂起进程并造成严重破坏。

I've spent quite a bit of time on this expression, but I'm unsure how to fix the issue. Hopefully a Regex pro out there can lend a hand! Two part question:

我花了很多时间在这个表达式上,但是我不确定如何解决这个问题。希望有一个Regex专业人员能帮上忙!两部分的问题:

1) How can this regex pattern be improved so it does not hang when evaluating string "http://www.example.com/?a=1":

1)如何改进这个regex模式,使它在计算字符串“http://www.example.com/?a=1”时不会挂起:

Regex pattern:

正则表达式模式:

(?<URL>(\s|^)((?<Scheme>[A-Za-z]{3,9})[:][/][/])?([A-Za-z0-9-]+[.])+([A-Za-z]+){2,4}(?(Scheme)|[/])(((?:[\+~%\/.\w-_]*[/]?)?\??#?(?:[\w]*))?)*(\s|$))

I would suggest using this awesome online .Net Regex testing engine: http://regexhero.net/tester/

我建议使用这款很棒的在线。net Regex测试引擎:http://regexhero.net/tester/。

2) What can I do in my calling code to prevent/recover from Regex engine hangups? Here's the calling code:

2)在我的调用代码中,我可以做什么来防止/恢复Regex引擎hangups?调用代码:

        Regex linkParser = new Regex(UrlMatchRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Find matches and add them to the result
        foreach (Match m in linkParser.Matches(message))
        {
            result.Add(m.Value.Trim());
        }

I've spent quite a bit of time on this particular Regex pattern, and have tried at least 7 alternates I've found (including most from this page: http://mathiasbynens.be/demo/url-regex). I would prefer to improve on my existing pattern, rather than use an entirely different one, but I'm open to options.

我已经在这个特定的Regex模式上花了相当长的时间,并尝试了至少7种我发现的交替模式(包括这个页面的大部分内容:http://mathiasbynens.be/demo/url-regex)。我宁愿改进我现有的模式,而不是使用完全不同的模式,但我愿意接受各种选择。

Final Regex v1:

最后的Regex v1:

After a few revisions, with some help from below, my final regex match looks like this:

经过几次修改之后,在下面的帮助下,我最后的regex匹配是这样的:

(?<URL>((?<=\s)|^)((?<Scheme>[A-Za-z]{3,9})[:][/][/])?([A-Za-z0-9-]+[.])+[A-Za-z]{2,4}(?(Scheme)|[/]?)(((?:[\+~%\/.\w-_]*[/]?)?\??#?&?(?:[\w=]*))?)*((?=\s)|$))

**Regex v2: Updated to include a set list of domains, port numbers, hashtags, but does not pull in trailing slashes

**Regex v2:更新为包含域、端口号、hashtag的集合列表,但不拖尾斜杠

(?<URL>((?<=\b)|^)((?<Scheme>[A-Za-z]{3,9})[:][/][/])?([A-Za-z0-9-]+[.])+((?<TLD>\b(aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mn|mn|mo|mp|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|nom|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ra|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw|arpa)\b))+(\/?)+((((?:[:\+~%/.\w-_\/])?[\?]?[#]?[&]?(?:[\w=]*))?)+(?=\?|\b)))

Test cases: this is a test of #

测试用例:这是一个#的测试

Should not match:

应该不匹配:

like when you a/b test something
this sentence ends with a/
just a #hashtag

Should match:

应该匹配:

sos.me extra
sos.me. extra <-- not period
sos.me, extra <-- not comma
sos.me/ extra <-- should match traililng /
sos.me/#hashtag? extra <-- not questionmark
sos.me? extra <-- not questionmark
www.sos.me? extra <-- not questionmark
sos.me/abcde extra
sos.me/abcde#hashtag extra
sos.me/abcdf/0 extra
sos.me/abcdf/0#hashtag extra
sos.me/something.aspx extra
sos.me/something.aspx#hashtag extra
http://something.com: extra <-- not colon
sos.me/something.aspx?name=value extra
sos.me/something.aspx?name=value#hashtag extra
http://something.com extra
https://something.com extra
http://something.com:80 extra
http://something.com:80/ extra <-- should match trailing /
http://something.com:80/?a=v&1=2 extra
http://something.com:80/?a=v&1=2#hashtag extra
http://something.com:80/?a=v&1=2# extra <-- should match trailing #

1 个解决方案

#1


5  

QUESTION 1

问题1

This is causing catastrophic backtracking:

这导致了灾难性的回溯:

([A-Za-z]+){2,4}

And:

和:

[\+~%\/.\w-_]*[/]?

I'm guessing you meant:

我猜你的意思:

([A-Za-z]{2,4})

And:

和:

[\+~%\/.\w-_]*

Your regex does not currently match URLs with equal signs, which is why the catastrophic backtracking happens in the first place:

您的regex当前不匹配具有相等符号的url,这就是为什么首先发生灾难性回溯的原因:

\??#?(?:[\w]*)

does not match '?a = 1' because \w does not include '='. You can fix this pretty easily:

不匹配”?a = 1',因为w不包含'='。你可以很容易地解决这个问题:

\??#?(?:[\w=%]*)

(I threw '%' in there too)

(我也加了%)

Also, your regex is matching the whitespace before and after your URL. You may prefer lookarounds to \s as this will match a position before or after whitespace rather than the whitespace itself:

另外,您的正则表达式在您的URL之前和之后与空格匹配。您可能更喜欢看空,因为这将匹配空格之前或之后的位置,而不是空格本身:

(?<URL>((?<=\s)|^)((?<Scheme>[A-Za-z]{3,9})[:][/][/])?([A-Za-z0-9-]+[.])+[A-Za-z]{2,4}(?(Scheme)|[/])(((?:[\+~%\/.\w-_]*[/]?)?\??#?(?:[\w=]*))?)*((?=\s)|$))

QUESTION 2

问题2

There's nothing you can do to detect or recover from a catastrophically backtracking regular expression. The best you could try is spinning the regex off into an independent thread and then terminating the thread after a certain timeout. Exactly how to do that would be an entirely different question, but it's not difficult to find tutorials online for .NET.

对于从灾难性的回调正则表达式中检测或恢复,您无能为力。您可以尝试的最好方法是将regex旋转到一个独立的线程中,然后在某个超时后终止该线程。具体怎么做将是一个完全不同的问题,但是在。net上找到教程并不难。

See:

看到的:

#1


5  

QUESTION 1

问题1

This is causing catastrophic backtracking:

这导致了灾难性的回溯:

([A-Za-z]+){2,4}

And:

和:

[\+~%\/.\w-_]*[/]?

I'm guessing you meant:

我猜你的意思:

([A-Za-z]{2,4})

And:

和:

[\+~%\/.\w-_]*

Your regex does not currently match URLs with equal signs, which is why the catastrophic backtracking happens in the first place:

您的regex当前不匹配具有相等符号的url,这就是为什么首先发生灾难性回溯的原因:

\??#?(?:[\w]*)

does not match '?a = 1' because \w does not include '='. You can fix this pretty easily:

不匹配”?a = 1',因为w不包含'='。你可以很容易地解决这个问题:

\??#?(?:[\w=%]*)

(I threw '%' in there too)

(我也加了%)

Also, your regex is matching the whitespace before and after your URL. You may prefer lookarounds to \s as this will match a position before or after whitespace rather than the whitespace itself:

另外,您的正则表达式在您的URL之前和之后与空格匹配。您可能更喜欢看空,因为这将匹配空格之前或之后的位置,而不是空格本身:

(?<URL>((?<=\s)|^)((?<Scheme>[A-Za-z]{3,9})[:][/][/])?([A-Za-z0-9-]+[.])+[A-Za-z]{2,4}(?(Scheme)|[/])(((?:[\+~%\/.\w-_]*[/]?)?\??#?(?:[\w=]*))?)*((?=\s)|$))

QUESTION 2

问题2

There's nothing you can do to detect or recover from a catastrophically backtracking regular expression. The best you could try is spinning the regex off into an independent thread and then terminating the thread after a certain timeout. Exactly how to do that would be an entirely different question, but it's not difficult to find tutorials online for .NET.

对于从灾难性的回调正则表达式中检测或恢复,您无能为力。您可以尝试的最好方法是将regex旋转到一个独立的线程中,然后在某个超时后终止该线程。具体怎么做将是一个完全不同的问题,但是在。net上找到教程并不难。

See:

看到的: