查找和替换正则表达式的问题 [英] Find and Replace RegEx question
问题描述
我开始获得正则表达式的感谢一握到所有有很大的帮助这里SO与我的其他问题。但我仍然吸吮这个:
I am starting to get a grip on RegEx thanks to all the great help here on SO with my other questions. But I am still suck on this one:
我的代码是:
StreamReader reader = new StreamReader(fDialog.FileName.ToString());
string content = reader.ReadToEnd();
reader.Close();
和
我在一个文本文件正在读我想搜索这个文本和更改它(X和Y值始终遵循在我的文本文件互相):
I am reading in a text file and I want to search for this text and change it (the X and Y value always follow each other in my text file):
X17.8Y-1
但这文本也可以是 X16.1Y2.3 的(这些值将永远是X和Y之后不同)
But this text can also be X16.1Y2.3 (the values will always be different after X and Y)
我想改成这样
I want to change it to this
X17.8Y-1.G54
或
X(值),Y(值)G54
我正则表达式语句后面,但它不工作。
My RegEx statement follows but it is not working.
content = Regex.Replace(content, @"(X(?:\d*\.)?\d+)*(Y(?:\d*\.)?\d+)", "$1$2G54");
是否有人可以修改它为我这样它的工作原理,并会寻找X(通配符)Y(通配符)和X(价值),Y(值)G54取代它呢?
Can someone please modify it for me so it works and will search for X(wildcard) Y(Wildcard) and replace it with X(value)Y(value)G54?
推荐答案
您所需要的正则表达式
X[-\d.]+Y[-\d.]+
下面是如何在C#中使用它:
Here is how to use it in C#:
string content = "foo X17.8Y-1. bar";
content = Regex.Replace(content, @"X[-\d.]+Y[-\d.]+", "$0G54");
Console.WriteLine(content);
输出:
Output:
foo X17.8Y-1.G54 bar
这篇关于查找和替换正则表达式的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!