简体   繁体   中英

regex isn't working

I am using c# trying to use regex on a file path

string text = File.ReadAllText(@"batchFile.bat");
string result = Regex.Replace(text, @"D:\folder1\folder(\d+\.\d+\.\d+\.\d)\setup.exe", @"D:\folder1\folder" + newVersion + @"\setup.exe");
File.WriteAllText(@"batchFile.bat", result);

So the original file path could be

D:\folder1\folder123.234.56.7\setup.exe

and I'm trying to use regex so I can change it to any other version number such as 12.3.456.78

When I run this code it doesnt change

You have 2 problems: 1) unescaped literal backslash in several places and 2) unescaped . that matches any symbol but a newline.

When using a verbatim string literal in C# to declare a regex you should remember that to match a literal \\ you need to use two backslashes ( \\\\ ).

Here , your D:\\folder1\\folder(\\d+\\.\\d+\\.\\d+\\.\\d)\\setup.exe regular expression does not match due to the same reason.

When using double backslashes ( and escaped dot to match a literal . !) - D:\\\\folder1\\\\folder(\\d+\\.\\d+\\.\\d+\\.\\d)\\\\setup\\.exe - it works .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM