How to Regex search/replace only first occurrence in a string in .NET?

后端 未结 4 989
傲寒
傲寒 2020-11-29 10:46

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

4条回答
  •  -上瘾入骨i
    2020-11-29 11:45

    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:

    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.

提交回复
热议问题