为什么我的Regex.Replace字符串包含替换值的两倍? [英] Why does my Regex.Replace string contain the replacement value twice?
问题描述
我有以下字符串: aWesdE
,我想转换为 http://myserver.com/aWesdE.jpg
使用 Regex.Replace(字符串,字符串,字符串,RegexOptions)
I have the following string: aWesdE
, which I want to convert to http://myserver.com/aWesdE.jpg
using Regex.Replace(string, string, string, RegexOptions)
目前,我用这个code:
Currently, I use this code:
string input = "aWesdE";
string match = "(.*)";
string replacement = "http://myserver.com/$1.jpg";
string output = Regex.Replace(input, match, replacement,
RegexOptions.IgnoreCase | RegexOptions.Singleline);
结果是输出结束了为: http://myserver.com/aWesdE.jpghttp://myserver.com/.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
这篇关于为什么我的Regex.Replace字符串包含替换值的两倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!