我想编写一个正则表达式,它会递归地删除某些文件扩展名(不是全部)。要剥离的扩展名是.ready、.done和.error。应通过单个组项目提供匹配。
例如:
HelloWorld.xml --> HelloWorld.xml
<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e664b4242416e79415c424a00564342005c4b4f4a57" rel="noreferrer noopener nofollow">[email protected]</a> --> <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcf4d9d0d0d3fcebd3ced0d892c4d1d0" rel="noreferrer noopener nofollow">[email protected]</a>
Yaba_Daba-Doo.aaa.orig --> Yaba_Daba-Doo.aaa.orig
HelloWorld.xml.ready.error --> HelloWorld.xml
yogibear.xml.ready.done --> yogibear.xml
HelloWorld.bbb.done --> HelloWorld.bbb
Merry Chrismas.ready.yyy --> Merry Chrismas.ready.yyy
所以,我想出了以下简单的正则表达式 - ^(.+)(?:\.(?:ready|done|error))*$
唉,它没有按预期工作,因为 (.+)
似乎是一个贪婪匹配。
附注不幸的是,它可以是任何文件名。我唯一想要的就是修剪任何尾随的 .ready
、.done
和/或 .error
。我知道我可以用代码来做到这一点,但我有兴趣知道如何使用正则表达式来解决这个问题,因为我感觉这是可能的。
最佳答案
这看起来太简单了,所以肯定有问题,但无论如何我都会发布我的解决方案。
您只需要将第一组(.+)
中的+
替换为非贪婪版本的+?
即可。
最终的正则表达式变为: ^(.+?)(?:\.(?:ready|done|error))*$
您可以使用以下代码尝试一下:
string strRegex = @"^(.+?)(?:\.(?:ready|done|error))*$";
RegexOptions myRegexOptions = RegexOptions.None;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"Merry Chrismas.ready.yyy";
string strReplace = @"${1}";
return myRegex.Replace(strTargetString, strReplace);
关于c# - .NET:与正则表达式匹配时如何排除某些文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17996066/