我尝试过了match .*
用C#正则表达式,结果发现它匹配任何字符串两次: first the 完整的字符串,比第二次空字符串。我期望.*
在一场比赛中匹配所有内容。我完全困惑为什么会这样以及如何防止这种情况。
长话短说:我需要替换部分文件名,并且可以通过某个替换字符串无条件替换。使用空字符串作为模式将匹配并在字符串的每个字符之后放置替换,如中所述Regex.Replace。因此我将空字符串替换为.*
更换前。但这结果执行了替换双精度。
为了演示发生了什么,我使用了:
string input= "sometext";
string pattern= ".*";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches) {
Console.WriteLine("[{0}]", match.Groups[0].Value); }
产生:
[sometext]
[]
- 当它已经匹配整个字符串时,为什么它第二次匹配空字符串?
- 我必须使用什么正则表达式或标志才能仅获得单个匹配/替换?
Solution
Using
.+
匹配一个或多个字符
string text = "sometext";
string expression = ".+";
MatchCollection matches = Regex.Matches(text, expression);
foreach (Match match in matches) {
Console.WriteLine("[{0}]", match.Groups[0].Value); }
输出为
[sometext]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)