如何正则表达式搜索/替换仅第一次出现在 .NET 中的字符串中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/148518/
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
How to Regex search/replace only first occurrence in a string in .NET?
提问by spoulson
It seems the .NET Regex.Replace method automatically replaces all matching occurrences. I could provide a MatchEvaluator delegate that returns the matched string after the first replacement, rendering no change, but that sounds very inefficient to me.
似乎 .NET Regex.Replace 方法会自动替换所有匹配的事件。我可以提供一个 MatchEvaluator 委托,它在第一次替换后返回匹配的字符串,不呈现任何变化,但这对我来说听起来效率很低。
What is the most efficient way to stop after the first replacement?
第一次更换后最有效的停止方法是什么?
回答by bzlm
回答by spoulson
Just to answer the original question... The following regex matches only the first instance of the word foo:
只是为了回答原来的问题......下面的正则表达式只匹配单词 foo 的第一个实例:
(?<!foo.*)foo
(?<!foo.*)foo
This regex uses the negative lookbehind (?<!) to ensure no instance of foo is found prior to the one being matched.
此正则表达式使用负向后视 (?<!) 来确保在匹配之前没有找到 foo 的实例。
回答by Viktor Pless
You were probably using the static method. There is no (String, String, Int32) overload for that. Construct a regex object first and use myRegex.Replace.
您可能正在使用静态方法。没有 (String, String, Int32) 重载。首先构造一个正则表达式对象并使用 myRegex.Replace。
回答by Pini Cheyni
In that case you can't use:
在这种情况下,您不能使用:
string str ="abc546_$defg";
str = Regex.Replace(str,"[^A-Za-z0-9]", "");
Instead you need to declare new Regex instance and use it like this:
相反,您需要声明新的 Regex 实例并像这样使用它:
string str ="abc546_$defg";
Regex regx = new Regex("[^A-Za-z0-9]");
str = regx.Replace(str,"",1)
Notice the 1, It represents the number of occurrences the replacement should occur.
注意1,它表示替换应该发生的次数。

