views:

123

answers:

4

In C# VS2008 how to replace

intA = (int)obj.GetStr("xxx");

to

intA = int.Parse(obj.GetStr("xxx"));

I have thounds of lines code have this pattern. I just want to pass compile by using some regular expression.

A: 

Have you tried Search and Replace?

Search for 'intA = (int)obj.GetStr("', replace with 'intA = Convert.ToInt32(obj.GetStr("'.

Adrian Godong
And you'll still have to go line by line and add a trailing parenthesis ).
arul
Yeah, but you could always use the crazy as all heck VS regex syntax and do an easy enough replace.
Quintin Robinson
i can't simply do that because intA maybe intA, intB, intC....and obj maybe obj1, obj2, obj3....
CodeYun
@CodeYun: add that to the question clarify it.
Adrian Godong
@Quintin: VS regex really is "special", isn't it?
Otis
+1  A: 

I don't like the new version either. When you know you have a string, int.Parse() or int.TryParse() is probably more appropriate.

Joel Coehoorn
Yes, i totally agree with you. So how can I convert to int.Parse()
CodeYun
+2  A: 

Try search and replace using the following regex:

EDIT: Replace the AAA, BBB, CCC values with the appropriate method names you want to match and replace. Be careful of using the :i (identifier) match predicate, as that would match any method call - which you probably don't want.

Find: (looks for any call on any expression to GetStr)

\(int\){.+}\.{(GetStr|AAA|BBB|CCC)}\({.*}\);

Replace With:

Convert.ToInt32(\1.\2(\3));

or (as others have mentioned) replace with:

Int.Parse(\1.\2(\3));

LBushkin
Thanks LBushkin.Actrually I want to replace all methods in the same pattern not only apply to GetStr, can you make some small change for that?
CodeYun
Do you mean that you want to be able to convert types other than just int (like double, short, etc)? Or do you mean something else?
LBushkin
Do the other methods all have a single string parameter, like GetStr?
Otis
All methods just like this pattern:objQueueXML.AAA("//UserID");objQueueXML.BBB("//UserID");objQueueXML("//UserID");
CodeYun
Or more generically, identifier.methodname("stringparameter"). I posted a variation on this answer that seems to match any method name.
Otis
You may not want to make the RegEx to generic, otherwise you may find yourself replacing more than what you expect. I'll edit my post to include a version where the GetStr method is substituted with a list of method names you can define.
LBushkin
A: 

This is a variation on what LBushkin suggested:

find: \(int\){:i\.:i\(:q\)}
replace: int.Parse(\1)
Otis