简体   繁体   中英

C# Regular Expression Replace and Add to End

I'm trying to create a find/replace regular expression in C# to find strings that start with -i, then contain any number of digits (no spaces) and then replace the -i with an empty string, but also add 2 spaces to the end to make up for removing the -i (it is a fix length file).

Right now, I am doing this to replace the text without adding the spaces at the end:

File.WriteAllText(textBox1.Text, Regex.Replace(File.ReadAllText(textBox1.Text), @"[-i]", ""));

An example line in the file is:

-i3598            00015

And I want the result to be:

3598              00015

Notice that the total length is the same before and after.

Thanks in advance!

Please try the following. It uses Regular Expressions Substitutions in the replacement pattern.

File.WriteAllText(
    textBox1.Text, 
    Regex.Replace(
        File.ReadAllText(textBox1.Text), 
        @"-i(\d+)", 
        "$1  "));

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