为什么我的Regex.Replace字符串包含替换值的两倍?我的、字符串、两倍、Replace

2023-09-03 01:02:03 作者:恍若隔世-

我有以下字符串: aWesdE ,我想转换为 https://m.xsw88.com/allimgs/daicuo/20230903/497.png.jpg 使用 Regex.Replace(字符串,字符串,字符串,RegexOptions)

I have the following string: aWesdE, which I want to convert to https://m.xsw88.com/allimgs/daicuo/20230903/497.png.jpg using Regex.Replace(string, string, string, RegexOptions)

目前,我用这个code:

Currently, I use this code:

string input = "aWesdE";
string match = "(.*)";
string replacement = "https://m.xsw88.com/allimgs/daicuo/20230903/498.png.jpg";
string output = Regex.Replace(input, match, replacement,
          RegexOptions.IgnoreCase | RegexOptions.Singleline);

结果是输出结束了为: https://m.xsw88.com/allimgs/daicuo/20230903/497.png.jpghttps://m.xsw88.com/allimgs/daicuo/20230903/499.png.jpg

所以,替换值显示正确,然后似乎是追加了 - 很奇怪。这是怎么回事吗?

So, the replacement value shows up correctly, and then appears to be appended again - very strange. What's going on here?

推荐答案

有实际的正则表达式2场比赛。你确定你的对手是这样的:

There are actually 2 matches in your Regex. You defined your match like this:

string match = "(.*)";

这意味着匹配零个或多个字符,所以你有2场比赛 - 空字符串和文本。为了解决它改变模式

It means match zero or more characters, so you have 2 matches - empty string and your text. In order to fix it change the pattern to

string match = "(.+)";

这意味着匹配一个或多个字符 - 在这种情况下,你只会得到一个匹配

It means match one or more characters - in that case you will only get a single match