7

I have some textual file with source code that contains object.<attribute>, where <attribute> can be an array, for example object.SIZE_OF_IMAGE[0], or a simple string. I want to use a regular expression in Vim to find all occurrences of object.<attribute> and replace them with self.<attribute_lowercase>, in which <attribute_lowercase> is the lowercase version of <attribute>.

I can use :%s/object.*/self./gc and perform the replacement manually, but it is very slow.

Here are some examples of the desired outcomes:

  • object.SIZE becomes self.size
  • object.SIZE_OF_IMAGE[0] becomes self.size_of_image[0]
1
  • Could you give us a realistic before/after example? As is, your question doesn't contain a single uppercase character in code samples so it's hard to see what you want to convert to lowercase, which makes it barely understandable. Commented Sep 19, 2018 at 16:02

4 Answers 4

17

You basically just need two things:

  • Capture groups :help /\( let you store what's matched in between \(...\) and then reference it (via \1, \2, etc.) in the replacement (or even afterwards in the pattern itself).
  • The :help s/\L special replacement action that makes everything following lowercase.

This gives you the following command:

:%substitute/\<object\.\(\w\+\)/self.\L\1/g 

Notes:

  • I've established a keyword start assertion (\<) at the beginning to avoid matching schlobject as well.
  • \w\+ matches letters, digits, and underscores (so it fulfills your example); various alternatives are possible here.
Sign up to request clarification or add additional context in comments.

Comments

1
sed -E 's/object\.([^ \(]*)(.*)/self.lowercase(\1)\2/g' file_name.txt 

above command considers that your attribute is followed by space or "("

you can tweek this command based on your need

Comments

0

Based on your comment above that the attribute part "finishes by space or [ or (" you could match it with:

/object\.[^ [(]* 

So, to replace it with self.attribute use a capturing group and \L to make everything lowercase:

:%s/\vobject\.([^ [(]*)/self.\L\1/g 

Comments

-1

In the command mode try this

:1,$ s/object.attribute/self.lowercase(attribute)/g 

3 Comments

I think OP is trying to change object.WHATEVER_THING to self.whatever_thing
attribute can be any string
@ChristianGibbons exactly but WHATEVER_THIN that finishes by space or [ or (

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.