Search code examples
regexnotepad++

How to replace every instance of a variable length value in a fixed length file?


In the below example - This is a fixed length file that I am looking to FIND any row that begins with "10" and has an "M" 9 positions later. When these types of records are found, I need to replace just the first name with the word Test which is found 35 positions later.

10123456789M 00002345678                       Tom Jones                           123 Main St
10123456789A 00002345678                       Debra Sally                         123 Main St
20123456789M 00002345678                       Michael Sampson                     123 Main St
10123456789M 00002345678                       Jonathan Smith                      123 Main St

As described so far, I can achieve this with the following regex in FIND and REPLACE

^(10(?:.{9}M).{35})(.*?) 
(\1)TEST 

The problem I'm having is that it is a fixed length file and using the above will mess up the starting position of the following address data. See the below is my results. Is there a way to find and replace a variable length value in a fixed length file using Regex in Notepad++?

10123456789M 00002345678                       TEST Jones                           123 Main St
10123456789A 00002345678                       Debra Sally                         123 Main St
20123456789M 00002345678                       Michael Sampson                     123 Main St
10123456789M 00002345678                       TEST Smith                      123 Main St

Solution

  • Regex is not very suited for that exact purpose. The closest to what you might be able to use I can come up with is:

    (^10.{9}M.{35}).{5}
    \1TEST_
    

    (use space instead of _)

    to get

    enter image description here

    Unfortunately this will mangle the names. Essentially you capture all up to the name into \1 and not capture the next 5 whatevers. Then you replace all with whatever was captured + TEST + Space: \1TEST

    10123456789M 00002345678                       TEST ones                           123 Main St
    10123456789A 00002345678                       Debra Sally                         123 Main St
    20123456789M 00002345678                       Michael Sampson                     123 Main St
    10123456789M 00002345678                       TEST han Smith                      123 Main St