简体   繁体   English

如何仅使用.Net Regex.Replace替换第一个匹配项

[英]How to replace the first match only using .Net Regex.Replace

Regex.Replace("a b c a b c", "a", "*")

returns 退货

"* b c * b c"

Is there a simple way to replace only the first occurence, such that the result is 有没有一种简单的方法可以只替换第一次出现的结果,从而得到

"* b c a b c"

Cannot find a RegExOption that would limit the replacement. 找不到会限制替换的RegExOption。 In particular 尤其是

Regex.Replace("a b c a b c", "a", "*", RegexOptions.Multiline)
Regex.Replace("a b c a b c", "a", "*", RegexOptions.Singleline)

do not make any difference - obviously. 没有任何区别-很明显。 There are not much more options however. 但是,没有更多选择。

Use the appropriate overload 使用适当的重载

Regex rgx = new Regex("a");
string result = rgx.Replace("a b c a b c", "*", 1); // * b c a b c

Use capturing group along with the starting anchor. 将捕获组与起始锚一起使用。

Regex.Replace("a b c a b c", "^([^a]*)a", "$1*")

DEMO 演示

^([^a]*) captures all the characters which exists before the first a . ^([^a]*)捕获第a之前存在的所有字符。 And the following a on the above regex matches only the first a . 并且上述正则表达式上的以下a仅匹配第a So by replacing the matched chars with the characters present inside the group index 1 plus * will give you the desired output. 因此,通过将匹配的字符替换为组索引1加*内的字符,将为您提供所需的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM