开发者

Find and Replace RegEx question

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(conte开发者_Python百科nt, @"(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?


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


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.


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.


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:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜