测试"&的endsWith QUOT;有效地与正则表达式 [英] testing for "EndsWith" efficiently with a Regex

查看:340
本文介绍了测试"&的endsWith QUOT;有效地与正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要建立一个正则表达式(.NET语法),以确定是否一个字符串一个特定的值结束。 。特别是我需要测试文件是否有特定扩展名(或一组扩展)

I need to build a Regex (.NET syntax) to determine if a string ends with a specific value. Specifically I need to test whether a file has a specific extension (or set of extensions).

我试图用修复代码:

.*\.(png|jpg|gif)$

这是在我的情况下(大概是由于回溯失败比赛可怕慢

which is hideously slow for failed matches in my scenario (presumably due to the backtracking.

只需除去。* (这是很好的,因为只有API火柴测试和不提取任何东西)开头使得正则表达式更有效。

Simply removing the .* (which is fine since the API only tests for matches and doesn't extract anything) at the beginning makes the regex much more efficient.

它仍然感觉这是非常低效的。我失去了一些东西明显在这里?

It still feels like it is pretty inefficient. Am I missing something obvious here?

不幸的是,我不控制有问题的API,所以我需要一个正则表达式来做到这一点,即使我通常不会考虑的正则表达式是这份工作的合适工具。

Unfortunately, I don't control the API in question so I need a regex to do this even though I wouldn't normally consider regex to be the right tool for the job.

我也做了一些测试,使用 RegexOptions.RightToLeft ,我发现我能挤多一点表现出来我的测试案例与 ^ * \。(PNG | JPG | GIF)$ ,但我不能找到一种方法来指定正则表达式本身的字符串中的从右至左选项,所以我不认为我可以使用它。

I also did some tests using the RegexOptions.RightToLeft and found that I could squeeze a little more performance out of my test case with ^.*\.(png|jpg|gif)$, but I can't find a way to specify the RightToLeft option within the string of the regex itself so I don't think I can use it.

推荐答案

我没有到C#访问,所以我不能试试这个...但你应该能够避免过多回溯迫使引擎查找该字符串的结尾,再匹配扩展:

I don't have access to C# so I can't try this... but you should be able to avoid too much backtracking by forcing the engine to find the end of the string first, then matching the extensions:

$(?<=\.(gif|png|jpg))

我不知道的效果look-背后对性能,虽然。

I'm not sure of the effect the look-behind has on performance, though.

这篇关于测试&QUOT;&的endsWith QUOT;有效地与正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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