Find and Replace RegEx question

穿精又带淫゛_ 提交于 2019-12-12 16:23:54

问题


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?


回答1:


The regular expression you need is:

X[-\d.]+Y[-\d.]+

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



回答2:


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:

(X[0-9.-]+Y[0-9.-]+)

And the replacement is

$1G54

This will work as long as a value pair is not directly followed by a digit, period or a dash.




回答3:


To be picky about the input, you could use

string num = @"-?(?:\d+\.\d+|\d+\.|\.\d+|\d+)";
content = Regex.Replace(content, "(?<x>X" + num + ")(?<y>Y" + num + ")", "${x}${y}G54");

Is there a reliable terminator for the Y value? Say it's whitespace:

content = Regex.Replace(content, @"(X.+?)(Y.+?)(\s)", "$1$2G54$3");

How robust does the code need to be? If it's rewriting debugging output or some other quick-and-dirty task, keep it simple.




回答4:


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.




回答5:


It looks like you just need to support optional negative values:

content = Regex.Replace(content, @"(X-?(?:\d*\.)?\d+)*(Y-?(?:\d*\.)?\d+)", "$1$2G54");


来源:https://stackoverflow.com/questions/2806789/find-and-replace-regex-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!