RegEx for replacing abc_def with abcDef entire word avoiding R.id.abc_def

Viewed 48

I'm trying to migrate from Kotiln synthetics to DataBinding.

So I'm trying to replace stuff like input_layout_phone_number with binding.inputLayoutPhoneNumber.

I got the part with replacing input_layout_phone_number with inputLayoutPhoneNumber, but I can only replace each underscore alone.

Also, something like R.string.abc_def gets included under this RegEx I'm using, also KEY_ABC

Find : _(w)

Replace : \U$1

Any idea how I can replace the entire word, and only find the words that do not have a . before them? Maybe also replace the entire word at once

Example :

input_text_field_layout
R.id.input_text_field_layout
TEXT_FIELD_LAYOUT

Expected output :

inputTextFieldLayout
R.id.input_text_field_layout
TEXT_FIELD_LAYOUT

Preferred output :

binding.inputTextFieldLayout
R.id.input_text_field_layout
TEXT_FIELD_LAYOUT
1 Answers

In Android Studio, you can use

(\G(?!^)[^\W_]*|\b(?<!\.)(?![A-Z_]+\b)[^\W_]+)_([^\W_])

Replace with $1\U$2. See the regex demo.

Details:

  • (\G(?!^)[^\W_]*|\b(?<!\.)(?![A-Z_]+\b)[^\W_]+) - Group 1 ($1): either the end of the previous successful match and then any zero or more word chars other than _ or a word boundary not immediately preceded with a . char, and then one or more word chars other than an underscore (with the exception of words only consisting of ALLCAPS letters and underscores, see (?![A-Z_]+\b) negative lookahead)
  • _ - an underscore
  • ([^\W_]) - Group 2: a word char minus _

In Visual Studio Code, you can use

(?<=\b(?<!\.)(?=[a-z_]+\b)\w+)_([^\W_])

Replace with \U$1. Make sure the Aa option (Match case) is ON.

Details:

  • (?<=\b(?<!\.)(?=[a-z_]+\b)\w+) - a location that is immediately preceded with a word boundary and one or more word chars that are not immediately preceded with a dot (but the word must consist of lowercase letters or/and underscores)
  • _ - an underscore
  • ([^\W_]) - Group 1: a word char other than a _.

DEMO:

enter image description here

Related