简体   繁体   English

查找并替换为正则表达式C#

[英]find and replace with regex C#

    string subject = "/testfolder
    subject = Regex.Replace(subject, "|d|", "17");
    Console.Write(subject);

getting output as 17/17o17u17t17g17o17i17n17g17 获取输出为17 / 17o17u17t17g17o17i17n17g17

why is the above find and replace failing, it should do nothing but instead it's filling in the replace variable at every single space. 上面的查找和替换为什么失败,它什么都不做,而是在每个空格处填充replace变量。 Does it even require regular expression? 它甚至需要正则表达式吗?

You know that in |d| 您知道|d| the | | means or ? 手段or Try escaping it! 尝试转义! @"\\|d\\|"

Your regular expression was equivalent to "" (empty string). 您的正则表达式等效于"" (空字符串)。

This because you must see it as 这是因为您必须将其视为

(match of empty string) or (match of letter d) or (match of empty string)

always matched from left to right, stop at the first positive match. 总是从左到右匹配,在第一个正匹配处停止。 As we will see, just the first condition (match of empty string) is positive everywhere, so it won't ever go to the other matches. 正如我们将看到的,只是第一个条件(空字符串匹配)在任何地方都为正,因此它将永远不会进入其他匹配。

Now, the regex parser will try to match your regex at the start of the string. 现在,正则表达式解析器将尝试在字符串的开头匹配您的正则表达式。

It is at "/" (first character): does it match? 它在“ /”(第一个字符)处:是否匹配? is "" part of "/" ? "" "/"一部分? Yes (at least in the "mind" of the regex parser). 是的(至少在正则表达式解析器的“思想”中)。 Now the funny thing is that Regex.Replace will replace the matched part of the string with 17 ... But funnily the matched part of "/" is "" , so it will replace an imaginary empty string that is just before the "/" with "17" . 现在有趣的是Regex.Replace将用17替换字符串的匹配部分。但是有趣的是, "/"的匹配部分是"" ,因此它将替换在"/"之前的虚空字符串。 "/""17" So it will become "17/" 因此它将变为"17/"

Now it will go to the next character (because normally the regex will be tried starting at the end of the previous match, but with a caveat written below), the t , redo the same and replace it with "17t" , so we will have at this point: 现在它将转到下一个字符(因为通常会在上一场比赛的末尾开始尝试使用正则表达式,但下面会写上警告),请重新设置t ,并将其替换为"17t" ,因此我们将在这一点上有:

17/17t

and so on. 等等。

There is a last little trick (taken from msdn ) 最后一个小技巧(取自msdn

When a match attempt is repeated by calling the Matches method, the regular expression engine gives empty matches special treatment. 通过调用Matches方法重复进行匹配尝试时,正则表达式引擎将对空匹配项进行特殊处理。 Usually, the regular expression engine begins the search for the next match exactly where the previous match left off. 通常,正则表达式引擎将从下一个匹配的确切位置开始搜索下一个匹配。 However, after an empty match, the regular expression engine advances by one character before trying the next match. 但是,在空匹配之后,正则表达式引擎将前进一个字符,然后再尝试下一个匹配。

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

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