C# 如何使用正则表达式从字符串中删除模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19572463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:19:12  来源:igfitidea点击:

How to remove a pattern from a string using Regex

c#regexreplace

提问by toosensitive

I want to find paths from a string and remove them e.g. string1 = "'c:\a\b\c'!MyUDF(param1, param2,..) + 'c:\a\b\c'!MyUDF(param3, param4,..)...", I'd like a regex to find the pattern '[some path]'!MyUDF, and remove '[path]'. Thanks

我想从字符串中查找路径并删除它们,例如string1 = "'c:\a\b\c'!MyUDF(param1, param2,..) + 'c:\a\b\c'!MyUDF(param3, param4,..)...",我想要一个正则表达式来查找模式'[some path]'!MyUDF,并删除“[path]”。谢谢

Edit e.g. input string1 ="'c:\a\b\c'!MyUDF(param1, param2,..) + 'c:\a\b\c'!MyUDF(param3, param4,..)"; expected output "MyUDF(param1, param2,...) + MyUDF(param3, param4,...)" where MyUDF is a function name, so it consists of only letters

编辑例如 input string1 ="'c:\a\b\c'!MyUDF(param1, param2,..) + 'c:\a\b\c'!MyUDF(param3, param4,..)"; 预期输出 "MyUDF(param1, param2,...) + MyUDF(param3, param4,...)" 其中 MyUDF 是函数名称,因此它仅由字母组成

采纳答案by Anirudha

input=Regex.Replace(input,"'[^']+'(?=!MyUDF)","");


In case if the path is followed by ! and some other word you can use

如果路径后跟 ! 还有一些你可以使用的词

input=Regex.Replace(input,@"'[^']+'(?=!\w+)","");

回答by Magus

The feature you want, if you are dealing with file paths, is in System.Path.

如果您要处理文件路径,那么您想要的功能在 System.Path 中。

There are many methods there, but that is one of it's specific purposes.

那里有很多方法,但这是它的特定目的之一。

回答by Mike Perrenoud

Alright, if the !is always in the string as you suggest, this Regex !(.*)?\(will get you what you want. Here is a Regex 101to prove it.

好的,如果!总是按照您的建议出现在字符串中,那么这个正则表达式!(.*)?\(将满足您的需求。这是一个正则表达式 101来证明它。

To use it, you might do something like this:

要使用它,您可以执行以下操作:

var result = Regex.Replace(myString, @"!(.*)?\(");