I just converted a VB.net solution into C# solution. But lots of variables have been coverted like:
string var1 = (string)1;
string var2 = (string)intVar; //intVar is a int value
I just want to convert all (string)XXXX to XXXX.ToString() by using some Regular expressions or some other replace methods.
Can someome help me out?
find: \(string\){:a*}
replace: \1.ToString()
Back up your solution first!
The text editor Notepad++ has regular expression support. You may try something like: Replace [(]string[)][ ]*([^ .\t;/]*) with \1.ToString().
This turns this:
(string) xyz;
(string) abc.123;
(string)alf;
(string)argu ment
into this:
xyz.ToString();
abc.ToString().123;
alf.ToString();
argu.ToString() ment
This however, does not handle the case of (string) aFunction( obj1, obj2 ).
You may want to handle these by yourself first, or build another regexp.
I am not sure if you really want to do this as a mass conversion. As in all reality in your example, you should end up with the following.
string var1 = "1";
and
string var2 = intVar.ToString();
There is no need for your first example to be doing a cast, when it can be a string from the beginning.
Suggest you to use this one
Find: \(string\){(.*)}{:Po}
Replace: \1.ToString()\2
Good luck!
I am not too familiar with regex but I offer a warning instead. You might not want to replace all (string)xxx to xxx.toString() because (as you know I am sure) (string) is casting and a ToString() is a method call. You can only cast something as string if the object is a descendant of string. You can call ToString() if the implementor of the class overrode the ToString() method. If not then you are just going to get the default implementation.
Well, the reason that you get the extra code in the conversion, is that you don't have Option Strict On in the VB code. If you had, you wouldn't be able to do those implicit conversions in the first place.
So, the VB code should look like this, and the C# code would then look right in the conversion:
var1 As String = "1"
var2 As String = intVar.ToString
To fix this after the conversion is done is quite beyond what a regular expression is capable of. Sure, you could make an expression that would convert all (string)x to x.ToString(), but that would probably cause more problems that it fixed...
Related
I need to do some very light parsing of C# (actually transpiled Razor code) to replace a list of function calls with textual replacements.
If given a set containing {"Foo.myFunc" : "\"def\"" } it should replace this code:
var res = "abc" + Foo.myFunc(foo, Bar.otherFunc( Baz.funk()));
with this:
var res = "abc" + "def"
I don't care about the nested expressions.
This seems fairly trivial and I think I should be able to avoid building an entire C# parser using something like this for every member of the mapping set:
find expression start (e.g. Foo.myFunc)
Push()/Pop() parentheses on a Stack until Count == 0.
Mark this as expression stop
replace everything from expression start until expression stop
But maybe I don't need to ... Is there a (possibly built-in) .NET library that can do this for me? Counting is not possible in the family of languages that RE is in, but maybe the extended regex syntax in C# can handle this somehow using back references?
edit:
As the comments to this answer demonstrates simply counting brackets will not be sufficient generally, as something like trollMe("(") will throw off those algorithms. Only true parsing would then suffice, I guess (?).
The trick for a normal string will be:
(?>"(\\"|[^"])*")
A verbatim string:
(?>#"(""|[^"])*")
Maybe this can help, but I'm not sure that this will work in all cases:
<func>(?=\()((?>/\*.*?\*/)|(?>#"(""|[^"])*")|(?>"(\\"|[^"])*")|\r?\n|[^()"]|(?<open>\()|(?<-open>\)))+?(?(open)(?!))
Replace <func> with your function name.
Useless to say that trollMe("\"(", "((", #"abc""de((f") works as expected.
DEMO
I wrote VB.NET code like this:
d = Data.IndexOf("</a>", ("target='_top' class='ab1'>").Length() + s).
I want to write this in C#. When I wrote the above code in C#, it said there was an error with the Length keyword. How do I write the above code in C#?
Length is not a keyword in C# - it is either a property or an extension method on the object (like a string) that you are trying to manipulate.
So if it is a string you are using this will work:
myString.Length
(notice how the brackets are missing because it is a property).
You have an extra set of parentheses:
d = Data.IndexOf("</a>", "target='_top' class='ab1'>".Length + s)
Try that
Check this link out:
In it, you can easliy switch between C# to a VB good, to help you migrate:
http://msdn.microsoft.com/en-us/library/system.string.length.aspx#Y242
string rawConnString = Properties.Settings.Default.ConnectionString;
I want to do this with "rawConnString":
rawConnString.Replace("<<DATA_SOURCE>>", server);
rawConnString.Replace("<<INITIAL_CATALOG>>", "tempdb");
Then set the final string to variable finalConnString.
How would I go about doing this?
This is ASP .NET 4.0/C# btw.
string finalString = Properties.Settings.Default.ConnectionString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", "tempdb");
will do it all in one line of code. But it's uglier IMO because you'll have to scroll. The code in your question seems a LOT cleaner and more readable to me.
And doing it in one line of code won't help your performance at all. It should all compile down to the same MSIL either way. I'd leave it as you had it.
Not sure if this is what you're after, but you can chain them:
var finalConnString = rawConnString.Replace("<<DATA_SOURCE>>", server)
.Replace("<<INITIAL_CATALOG>>", "tempdb");
If you're looking to do it with a single method call, I don't think there's anything native to .NET. You can always create an extension method though. Here's a performance-conscious ReplaceMany implementation (signature .ReplaceMany(string[] oldValues, string[] newValues)).
This is frankly trivial; you have 90% of the code you need:
string rawConnString = Properties.Settings.Default.ConnectionString;
string finalConnString = rawConnString
.Replace("<<DATA_SOURCE>>", server)
.Replace("<<INITIAL_CATALOG>>", "tempdb");
To avoid using two back-to-back calls of Replace, you can use regular expressions. However, this is far less readable than the original:
string connString = Regex.Replace(
rawConnString
, "(<<DATA_SOURCE>>)|(<<INITIAL_CATALOG>>)"
, m => m.Groups[1].Success ? server : "tempdb"
);
Link to ideone.
you mean something like this
string tempString=rawConnString.Replace("<<DATA_SOURCE>>", server);
sting finalstring=tempString.Replace("<<INITIAL_CATALOG>>", "tempdb");
First, String.replace does not change the original string: it creates a new string. So you have to assign the return value to something. So the logically simplest thing to do is:
finalstring=rawConnString.Replace("<<DATA_SOURCE>>", server);
finalstring=finalstring.Replace("<<INITIAL_CATALOG>>", "tempdb");
Note that for the second replace, you want to start with the results of the first replace, not the original string.
As String.replace returns a string, and String.replace takes a string, you might find it easier to run them together:
finalstring=rawConnString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", "tempdb");
I have a string as follows:
ListViewSubItem: {Debian6/Debian6.vmx }
What would be the most efficient way of getting the following output:
Debian6/Debian6.vmx
int beginidx = haystack.IndexOf('{');
string needle = haystack.SubString(beginidx,
haystack.IndexOf('}') - beginidx + 1).Trim();
string result = Regex.Match("ListViewSubItem: {Debian6/Debian6.vmx }", #"(?<={)(.+?)(?=})").Value;
You can use a regex:
\{\s*(.*)\s*\}
The desired string will be in the first captured group (Match.Groups[1]).
Example:
string output = Regex.Match(input, #"\{\s*(.*?)\s*\}").Groups[1].Value;
As was pointed out, regexes are slower than plain string manipulation. If performance is an issue, and the string extraction is in a tight loop, then it may be better to use an optimized method. Otherwise, regex vs string is IMHO a matter of personal preference.
I'm going to guess you didn't generate that string yourself. So the question is, why parse it? This looks like the sort of question where you should take a step back and think of what you're trying to solve, and if another method might be cleaner.
I am not familiar with the ListViewSubItem class, but it seems like you have one of these and you have called ToString() on it. Now you are parsing the output of ToString() to see the model object your sub-item represents.
Does this not seem backwards to you? Maybe you should deal with the ListViewSubItem object itself (from a brief look at the documentation, what you want seems to be the Text property), rather than fiddling with what ToString() returns, which seems volatile and dependent on the implementation of that class's ToString() method (which, though likely not, could theoretically change from release to release). Not to mention corner cases like "what if the string contains the } character?"
For this in other reasons, as a general rule I think you should not have to deal with serialization when your data source is in memory the whole time.
So, in summary, if you have something like this:
ListViewSubItem item = /* ... */;
string s = item.ToString();
// TODO: parse {Debian} out of ListViewSubItem {Debian}
Why not this instead:
ListViewSubItem item = /* ... */;
string OS = item.Text;
I have a little chunk of code (see below) that is returning the string:
string.Format("{0}----{1}",3,"test 2");
so how do I get this to actually "Execute"? To run and do the format/replacement of {0} and {1}?
My Code snippet:
StringBuilder sb = new StringBuilder();
sb.Append("{0}----{1}\",");
sb.AppendFormat(ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
string sbStr = "=string.Format(\""+sb.ToString()+");";
yes, ReturnParamValue gives the actually value of the DTO.
Anyways, I've taken a look at the following (but it doesn't say how to execute it:
How to get String.Format not to parse {0}
Maybe, I just should put my code snippet in a method. But, what then?
Why are you including String.Format in the string itself?
If you're looking for a generic "let me evaluate this arbitrary expression I've built up in a string" then there isn't a simple answer.
If, instead, you're looking at how to provide the parameters to the string from a function call, then you've got yourself all twisted up and working too hard.
Try something like this, based on your original code:
string result
= string.Format(
"{0}----{1}",
ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
Though, this won't entirely work since your original code seems to be only providing a single value, and you have two values in your format string - the {0} will be replaced with the value from your function, and {1} left unchanged.
What output are you expecting?
Does your ReturnParamValue() function try to return both the label and the value in a single string? If it does, and if they're comma separated, then you could try this:
var value = ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
var pieces = string.Split(',');
string result
= string.Format( "{0}----{1}", pieces[0], pieces[1]);
Though this is seriously working too hard if ReturnParamValue() is a method you control.
Update Fri 6 August
Check out the declaration for string.Format() as shown on MSDN:
public static string Format(
string format,
params Object[] args
)
Unlike the special casing you might have seen in C for printf(), there's nothing special or unusual about the way string.Format() handles multiple parameters. The key is the params keyword, which asks the compiler to provide a little "syntactic sugar" where it combines the parameters into an array for you.
Key here is that the wrapping doesn't happen if you're already passing a single object[] - so if you wanted to, you could do something like this:
object[] parameters
= ReturnParamValues(siDTO, "siDTO.SuggestionItemID,siDTO.Title");
string result
= string.Format("{0}----{1}----{2}", parameters);
Though, if I saw something like this in any codebase I maintained, I'd be treating it as a code-smell and looking for a better way to solve the problem.
Just because it's possible doesn't mean it's advisable. YMMV, of course.
I don't think you can execute it. Java is not really a interpreted language.
You may make use of scripting languages (which can even embed in your Java app as I know, start from JDK6) for such purpose, like Groovy
You could use RegEx to parse the three parameters out of the string, and then pass them to a real, actual string.Format method :-)
It looks like what you want is something like this:
string sbStr = string.Format("{0}----{1}", siDTO.SuggestionItemID, siDTO.Title);
Maybe i didn't understand your question completely, but it sounds like you need to format a format-string. If that's true you could maybe try something like this:
int width = 5;
string format = String.Format("{{0,{0}}}----{{1,{0}}}", width);
string result = String.Format(format, "ab", "cd");
So the trick is simply to escape the { or } by using a double {{ or }}.