如何正则表达式查找/替换只有第一次出现在字符串中的.NET? [英] How to Regex search/replace only first occurrence in a string in .NET?

查看:293
本文介绍了如何正则表达式查找/替换只有第一次出现在字符串中的.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来.NET Regex.Replace方法会自动替换所有匹配的事件。我可以提供一个MatchEvaluator委托,返回匹配字符串的第一个更换后,呈现没有变化,但听起来非常低效的我。

什么是停止第一置换术后最有效的方法是什么?

解决方案

从<一个href="http://msdn.microsoft.com/en-us/library/system.text.regularex$p$pssions.regex.replace.aspx">MSDN:

 替换(字符串,字符串,Int32)将
 

  

在一个指定的输入字符串,替换字符串指定的最大数量的   与指定的字符串替换常规EX pression模式进行匹配。

这是不是你想要的?

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.

What is the most efficient way to stop after the first replacement?

解决方案

From MSDN:

Replace(String, String, Int32)

Within a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

Isn't this what you want?

这篇关于如何正则表达式查找/替换只有第一次出现在字符串中的.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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