C#正则表达式替换和* [英] C# Regex Replace and *
问题描述
我是一个Perl程序员做了一些的C#。面对关于零或更多的断言与Regex.Replace一个奇怪的问题,*。
I'm a perl programmer doing a bit of C#. Facing an odd issue with Regex.Replace in regard to the zero-or-more assertion, *.
说我想用一个字母来代替零个或多个字母。在Perl中,我能做到这一点:
Say I wanted to replace zero or more letters with a single letter. In perl, I could do this:
my $s = "A";
$s =~ s/\w*/B/;
print $s;
$s now = "B"
但是,如果我尝试做在C#中相同,像这样的:
But if I try and do the same in C#, like this:
string s = Regex.Replace("A", @"\w*", "B");
s now = "BB"
该文档不说的*字符不承认替换模式中的元字符
The docs do say "The * character is not recognized as a metacharacter within a replacement pattern"
为什么呢?而且没有任何变通,如果你想有点您正则表达式来啜了一些遗留下来的字符串,可能不存在(如。*?在终点)
Why? And is there any work around if you want a bit of your regex to slurp up some left over string which may not be there (like ".*?" on the end)
(这是一个愚蠢的例子,但你明白了吧)
(this is a silly example, but you get the point)
推荐答案
与启动模式^和$结束它你的问题就解决了。
Start your pattern with ^ and end it with $ and your problem is solved.
string s = Regex.Replace("AAAA", @"^\w*$", "B");
Console.Write(s);
另外 - 你可以停在0与 + 长度的字符串匹配code>运营商,而不是
*
运营商:
Alternatively - you can stop matching on 0 length strings with the +
operator instead of the *
operator:
string s = Regex.Replace("AAAA", @"\w+", "B");
Console.Write(s);
这篇关于C#正则表达式替换和*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!