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

编程入门 行业动态 更新时间:2024-10-25 14:29:59
本文介绍了为什么我的Regex.Replace字符串包含替换值的两倍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下字符串: aWesdE ,我想转换为 myserver/aWesdE.jpg 使用 Regex.Replace(字符串,字符串,字符串,RegexOptions)

I have the following string: aWesdE, which I want to convert to myserver/aWesdE.jpg using Regex.Replace(string, string, string, RegexOptions)

目前,我用这个code:

Currently, I use this code:

string input = "aWesdE"; string match = "(.*)"; string replacement = "myserver/$1.jpg"; string output = Regex.Replace(input, match, replacement, RegexOptions.IgnoreCase | RegexOptions.Singleline);

结果是输出结束了为: myserver/aWesdE.jpgmyserver/.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字符串包含替换值的两倍?

本文发布于:2023-11-04 00:47:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556498.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   两倍   Regex   Replace

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!