0

Say I have a for loop and a vector.

for(int x = 0; x < 10; ++x) {
    vector.at(x) = 0;
}

Is there a way to replace .at(x), with [x], without changing the text inside? Also it would need to work with any arbitrary text. I think there should be a way to do this with regex, but I don't know how.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
Patrick M
  • 57
  • 5
  • 1
    What if `x` is actually `someOtherVector.at(y)`? What if it's `myMap.at(y)`? Regex won't work with arbitrary text, but maybe your text is constrained enough and benign enough to be treatable with regex... – Max Langhof Sep 16 '19 at 16:52
  • Something like this (using `sed` since I don't have xcode): `sed -r 's/\.at\(([^)]+)\)/[\1]/g'` - but do check the result before saving. :) – Ted Lyngmo Sep 16 '19 at 17:03

1 Answers1

0

Use can try a sed based approach like below. However, this will only work for straight-forward search/replace patterns. If you think your code base may have more complex index expressions, e.g. something like vector.at( foo().at(bar()) ) then this approach will get complex. It may introduce subtle and unwanted code changes -- ensure to diff the files before and after running the sed !

if had a file (code.cc) with line like this:

vector.at(xx) ;  vector.at(YY) ;
vector.at( i - j) ;  vector.at(KKK - _LLL) ;

doing:

cat file.cc |  sed -e 's!.at(\([^)]*\))![\1]!g'

gives

vector[xx] ;  vector[YY] ;
vector[ i - j] ;  vector[KKK - _LLL] ;

Note, this regexp will not work for more complex lookups, eg, vector.at( foo() )

Darren Smith
  • 1,736
  • 12
  • 13
  • Any reason for `[a-zA-Z0-9_\-]*` instead of `.*`? – dtell Sep 16 '19 at 16:57
  • want to match only variable names, and not greedily eat the entire line (i.e. there could be two or more vector.at(..) on a single line – Darren Smith Sep 16 '19 at 16:59
  • Good point! Thanks! – dtell Sep 16 '19 at 17:00
  • although its fair point ... the thing inside the at(..) brackets could be more complex, eg, `vector.at(i - j)` .... this regex won't handle that – Darren Smith Sep 16 '19 at 17:02
  • True, you just have to make sure that you wont end up with something like `vector[x) = 0; vector.at(y];` Maybe some trick using `;` could be more accurate. But then again imagine a map lookup where `';'` serves as a key... – dtell Sep 16 '19 at 17:04
  • yeah, this is more complex ... I think it needs to properly parse the code, eg, vector.at( foo().at(bar()) ) etc ... and, the danger of running sed naively is that it might introduce subtle bugs. – Darren Smith Sep 16 '19 at 17:09