Search code examples
regexregex-lookarounds

Remove last occurrence of pattern and everything after that


I want to remove last occurrence of a pattern "\[uU]" and everything after it from a string.

Example:

input: ab00cd\u00FF\U00FF0000

output: ab00cd\u00FF

I am doing this currently with something like lastIndexOf and substring and I wonder if there is a Regex way to do it. I figure it might involve lookarounds?


Solution

  • Match \U that isn't followed by \U.

    You haven't said what language you're using, so the generic solution is:

    Search: \[uU](?!.*\[uU]).*
    Replace: <blank>
    

    The negative look-ahead (?!.*\[uU]) asserts that \U (or \u) do not appear anywhere after the leading match.