查找和替换正则表达式问题
感谢这里对我其他问题的所有大力帮助,我开始掌握 RegEx。但我仍然不喜欢这个:
我的代码是:
StreamReader reader = new StreamReader(fDialog.FileName.ToString());
string content = reader.ReadToEnd();
reader.Close();
我正在阅读一个文本文件,我想搜索该文本并更改它(X和Y值在我的文本文件中始终相互跟随):
X17.8Y-1.
但是这个文本也可以是X16.1Y2.3(X和Y后面的值总是不同的)
我想改变到这个
X17.8Y-1.G54
或
X(value)Y(value)G54
我的正则表达式语句如下,但它不起作用。
content = Regex.Replace(content, @"(X(?:\d*\.)?\d+)*(Y(?:\d*\.)?\d+)", "$1$2G54");
有人可以帮我修改它,以便它可以工作并搜索 X(通配符)Y(通配符)并将其替换为 X(值)Y(值)G54 吗?
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:
My code is:
StreamReader reader = new StreamReader(fDialog.FileName.ToString());
string content = reader.ReadToEnd();
reader.Close();
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.
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
or
X(value)Y(value)G54
My RegEx statement follows but it is not working.
content = Regex.Replace(content, @"(X(?:\d*\.)?\d+)*(Y(?:\d*\.)?\d+)", "$1$2G54");
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要的正则表达式是:
以下是在 C# 中使用它的方法:
输出:
The regular expression you need is:
Here is how to use it in C#:
Output:
文本文件中“X(值)Y(值)”之后是什么?一个空间?换行符?另一个“X(值)Y(值)”值对?
我不太擅长在正则表达式中使用快捷方式,例如 \d,也不熟悉 .NET,但我使用了以下正则表达式来匹配值对:
替换是
只要值对是,这就会起作用后面不直接跟数字、句点或破折号。
What comes after "X(value)Y(value)" in your text file? A space? A newline? Another "X(value)Y(value)" value pair?
I'm not very good using shortcuts in regexes, like \d, nor am I familiar with .NET, but I had used the following regex to match the value pair:
And the replacement is
This will work as long as a value pair is not directly followed by a digit, period or a dash.
要对输入挑剔,您可以使用
Y 值是否有可靠的终止符?假设它是空白:
代码需要有多健壮?如果它正在重写调试输出或其他一些快速而肮脏的任务,请保持简单。
To be picky about the input, you could use
Is there a reliable terminator for the Y value? Say it's whitespace:
How robust does the code need to be? If it's rewriting debugging output or some other quick-and-dirty task, keep it simple.
我知道这并不能直接回答您的问题,但您应该查看 Expresso。它是一个 .NET 正则表达式工具,允许您调试、测试和微调复杂的表达式。这是一个救星。
更多的是自己动手的答案,但即使有人在这里给你答案也会很有帮助。
I know this doesn't answer your question directly, but you should check out Expresso. It's a .NET Regular Expression Tool that allows you to debug, test, and fine-tune your complex expressions. It's a life-saver.
More of a do-it yourself answer, but it'll be helpful even if someone gives you an answer here.
看起来您只需要支持可选的负值:
It looks like you just need to support optional negative values: