Search code examples
csvsearchreplacenotepad++

Regex Search and Replace specific text on a csv using Notepad++


I need to do a search and replace on a csv file using regex on Notepad++ or TextPad to replace the text on a specific column if another text is met. For example, I have this line:

Search for price 50.75 only if 8x8 and "1" is met:

sample,,,,,,,,50.75,true,,,InStock,,,,,#593D24:WHITE PLASTIC,,,8x8,,,"1"" inch"
sample,,,,,,,,27.30,true,,,InStock,,,,,#593D24:WHITE PLASTIC,,,8x8,,,"2"" inch"
sample,,,,,,,,50.75,true,,,InStock,,,,,#593D24:WHITE PLASTIC,,,12x12,,,"0"" inch"

Replace only the price with 75.25:

sample,,,,,,,,75.25,true,,,InStock,,,,,#593D24:WHITE PLASTIC,,,8x8,,,"1"" inch"

Any help would be greatly appreciated.

Thanks in advance.


Solution

  • Use look arounds:

    Search:

    (?<=,)50.75(?=,.*?\b8x8\b.*?"1"")
    

    Replace:

    75.25
    

    See live demo.

    Regex breakdown:

    • (?<=,) means the preceding char was a comma
    • (?=,.*?\b8x8\b.*?"1"") means the following chars are a comma and later 8x8 and later "1""

    The look behind for a comma ensures amounts like 250.75 don't match.

    The word boundaries \b ensure dimensions like 18x8 don't match.

    Using reluctant quantifier .*? makes it more efficient, as .* would consume all input to the end before backtracking to the next character.