regextextmateoniguruma

Regex to Find a Word Inside Curly Braces


I need a way to search the text using RegEx and find a word thats inside Latex command (which means that it's inside curly braces)

Here is the example:

Tarzan is my name and everyone knows that {Tarzan loves Jane}

Now if you search for regex: ({[^{}]*?)(Tarzan)([^}]*}) and replace it with $1T~a~r~z~a~n$3

This will replace only the word Tarzan inside curly braces and ignore the other instance! This is as far as I came.

Now what I need is something to do the same with the following example:

Tarzan is my name and everyone knows that {Tarzan loves Jane} but she doesn't know that because its written with \grk{Tarzan loves Jane}

In this example I need just the last mention of "Tarzan" to be replaced (the one within \grk{})

Can someone help me to modify the above RegEx search to do only that?


Solution

  • You can try to use this pattern:

    (?:\G(?!\A)|\\grk{)[^}]*?\KTarzan
    

    demo

    details:

    (?:
        \G(?!\A)  # contiguous to a previous match
      |           # OR
        \\grk{    # first match
    )
    [^}]*?        # all that is not a } (non-greedy) until ...
    \K            # reset the start of the match at this position
    Tarzan        # ... the target word
    

    Note: \G matches the position after the previous match, but it matches the start of the string too. That's with I add (?!\A) to prevent a match at the start of the string.

    Or you can use: \\grk{[^}]*?\KTarzan with multiple pass.