Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Regex.Replace to keep characters that can be vary

Tags:

c#

regex

replace

I have the following:

string text = "version=\"1,0\"";

I want to replace the comma for a dot, while keeping the 1 and 0, BUT keeping in mind that they be different in different situations! It could be version="2,3" .

The smart ass and noob-unworking way to do it would be:

           for (int i = 0; i <= 9; i++)
            {
                for (int z = 0; z <= 9; z++)
                {
                    text = Regex.Replace(text, "version=\"i,z\"", "version=\"i.z\"");
                }
            }

But of course.. it's a string, and I dont want i and z be behave as a string in there.

I could also try the lame but working way:

text = Regex.Replace(text, "version=\"1,", "version=\"1.");
text = Regex.Replace(text, "version=\"2,", "version=\"2.");
text = Regex.Replace(text, "version=\"3,", "version=\"3.");

And so on.. but it would be lame.

Any hints on how to single-handedly handle this?

Edit: I have other commas that I don't wanna replace, so text.Replace(",",".") can't do

like image 528
ng80092b Avatar asked Dec 19 '22 05:12

ng80092b


2 Answers

You need a regex like this to locate the comma

Regex reg = new Regex("(version=\"[0-9]),([0-9]\")");

Then do the repacement:

text = reg.Replace(text, "$1.$2");

You can use $1, $2, etc. to refer to the matching groups in order.

like image 127
Petar Ivanov Avatar answered Dec 22 '22 00:12

Petar Ivanov


(?<=version=")(\d+),

You can try this.See demo.Replace by $1.

https://regex101.com/r/sJ9gM7/52

like image 27
vks Avatar answered Dec 22 '22 01:12

vks