开发者

Replacing .at() with [] throughout my code

I'm a C++ user and got some code that uses .at() to get bound checking on the STL vectors. Now开发者_运维百科 I'd like to change them to standard []. Does anyone know of a script that could do this? It doesn't have to be a super general script — most of the cases are .at(i) or perhaps .at(a*i+j) — but there are too many of them to do by hand.


Use this Perl operator:

s/\.at\(([^)]+)\)/[$1]/g

The s/// operator in Perl is a "substitute" (find/replace). In the first set of //, you specify the regular expression to match. The second // is the text to replace or substitute that match with.

In this case, I'm finding any instance of ".at(anything-but-a-close-paren)" and replace it with "[what-was-in-those-parens]".

As a one-liner,

perl -pe's/\.at\(([^)]+)\)/[$1]/g' in.cpp > out.cpp

If you use Visual Studio, do this in the Find/Replace prompt:

Find What: \.at\({[^)]+}\) Replace with: \[\1\]

Enable Regular Expressions and you're good to go.


sed -i 's,\.at(\([^\)]*\)),[\1],g' *.h *.cpp

should work for most simple expressions. However, if you use parentheses inside the parameter to at(), this will not work.

grep 'at(.*).*)' *.h *.cpp

helps you to identify these cases and convert them before running said sed script.

P.S. Keep a backup around (e.g. via a VCS) if you let sed operate in-place like here.

EDIT: Should have tested that sed script before posting. Fixed now, and tested.


sed -e 's/\.at(\([^)]*\))/\[\1]/g
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜