Replace a specific word only within the first set of ( )



  • I want to replace “sharp” to ~sharp whenever it appears within the first set of ( ). It should not replace it in anything before or after the first set of “(” “)” on a line.

    here is the before

    u: ( << eating sharp things >> ) This is a slightly less common one compared to others on this list, but it’s still one of the most common dreams. To dream about eating broken glass (or anything sharp and horrible) means you’re having trouble saying what you want to say.

    Here is the after

    u: ( << eating ~sharp things >> ) This is a slightly less common one compared to others on this list, but it’s still one of the most common dreams. To dream about eating broken glass (or anything sharp and horrible) means you’re having trouble saying what you want to say.

    Seem like a small change, but I have about 250K such updates that follow this pattern.

    I tried through about 50 examples, and I have not found any solution.
    Any help would be appreciated!



  • @Michael-Canavan said:

    I want to replace “sharp” to ~sharp whenever it appears within the first set of ( )

    Welcome Michael to Notepad++ community. Yes it does look a bit tricky. Boiling it down to a sentence, you want to cross the line character by character so long as no ( found. Then once that is found you want to search for the word sharp, again so long as no ) found. By writing it this way it does become easier.

    So my regex to be used in the “Replace” function is:
    Find What:^([^(]+?\([^)]+?)sharp
    Replace With:\1~sharp

    Search mode must be “regular expression” and wrap around should be ticked. To give some background of the regex.
    ^[^(]+? means grab characters so long as no ( found.
    \([^)]+? means, first grab the (, then more characters so long as a ) is not found.
    sharp obviously means find the word sharp.
    Note that the first 2 portions are encapsulated by () so that means we capture and hold those. We don’t need to capture the word sharp as we will be replacing that with ~sharp anyways. The \1 is the portion we captured earlier, so we replace that back.

    Give that a go and please do come back to the forum and post how you got on. If issues we need to know what it did not work on so that perhaps we can alter the regex to better suit the conditions. We ALL love a good ending!

    Terry

    Terry



  • @Terry-R said:

    \1~sharp

    EXCELLENT! It worked without a hitch. Thank you so much for your help, it is greatly appreciated!
    You can not imagine the pain your solution relieved.


Log in to reply