Search code examples
stringtextreplace

Replace Text in String


I'm trying to write a RegEx expression to replace specific text in a string where parts of the text are variable.

For example, the text strings are the following:

XX                23080900012308091439
XX                23080900012308011439
XX                23080900012308231439
XX                23080900012308151439

For a text string that starts with XX and ends with 1439, I want to replace 1439 with another 4-digit number (like 1234).

After the find-and-replace, the output would be:

XX                23080900012308091440
XX                23080900012308011440
XX                23080900012308231440
XX                23080900012308151440

Each time I try to write a RegEx to find the text, it's giving me all instances of "1439" (not just ones in a text string that starts with XX).

  1. Is there a way to restrict the search to strings that start with XX and end with 1439?
  2. Is there a way to only make the replacement if the string starts with XX?

Edited to add:

This is what has worked so far:

Find: ^(XX\s+)(\d{16})(.*)$

Replace: $1$21440

https://regex101.com/r/dD0E4t/1

I think I'm getting close, but I can't get a text editor to recognize the syntax.

Thanks for any help you can provide!


Solution

  • If you are using Notepad++ (make sure you select Regular expression), you use a single capture group:

    ^(XX\s+\d{16})1439$
    

    Explanation

    • ^ Start of string
    • (XX\s+\d{16}) Capture group 1, match XX followed by 1+ whitespace chars and 16 digits
    • 1439
    • $ End of string

    (note that you can also use \h+ instead of \s+ to match 1 or more horizontal whitespace chars)

    In the replacement use the value of capture group 1 followed by 1440 like \11440

    Regex demo

    Or you can make use of \K to forget what is matched so far, and use only 1440 in the replacement.

    ^XX\s+\d{16}\K1439$
    

    Regex demo

    enter image description here