Search code examples
regexandroid-studiouppercaseregexp-replace

Regex replace in Android Studio to UPPERCASE


Does anyone know if it is possible to perform a Regular Expression replace operation in AndroidStudio where a particular match can be converted to uppercase?

Example:

I want to search find all occurrences of;

Log.i
Log.e
Log.d

...and replace them with :

if ( LogConfig.LOGI ) Log.i
if ( LogConfig.LOGE ) Log.e
if ( LogConfig.LOGD ) Log.d

In other words, some of the replacements are as is (no brainer) but others must be CAPITALIZED.

If this is possible, how do I do this?


Solution

  • You may use

    (Log)\.([ied])
    

    Replace with if ( LogConfig.\U$1$2\E ) $0. See the regex demo.

    If you need to match Log.e as a whole word, add word boundaries, \b(Log)\.([ied])\b.

    Details

    • (Log) - Capturing group 1: Log
    • \. - a dot
    • ([ied]) - a letter i, e or d.

    The \U$1$2\E means:

    • \U - start turning to upper case all that follows:
      • $1 - Group 1 value
      • $2 - Group 2 value
    • \E - stop turning to uppercase.