Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to 'sscanf()' in .NET?

Tags:

string

.net

The .NET Framework gives us the Format method:

string s = string.Format("This {0} very {1}.", "is", "funny");
// s is now: "This is very funny."

I would like an "Unformat" function, something like:

object[] params = string.Unformat("This {0} very {1}.", "This is very funny.");
// params is now: ["is", "funny"]

I know something similar exists in the ANSI-C library (printf vs scanf).

The question: is there something similiar in C#?

Update: Capturing groups with regular expressions are not the solution I need. They are also one way. I'm looking for a system that can work both ways in a single format. It's OK to give up some functionality (like types and formatting info).

like image 223
doekman Avatar asked Jan 29 '09 16:01

doekman


5 Answers

There's no such method, probably because of problems resolving ambiguities:

string.Unformat("This {0} very {1}.", "This is very very funny.")
// are the parameters equal to "is" and "very funny", or "is very" and "funny"?

Regular expression capturing groups are made for this problem; you may want to look into them.

like image 113
mqp Avatar answered Nov 14 '22 06:11

mqp


Regex with grouping?

/This (.*?) very (.*?)./
like image 5
annakata Avatar answered Nov 14 '22 07:11

annakata


If anyone's interested, I've just posted a scanf() replacement for .NET. If regular expressions don't quite cut it for you, my code follows the scanf() format string quite closely.

You can see and download the code I wrote at http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net.

like image 5
Jonathan Wood Avatar answered Nov 14 '22 07:11

Jonathan Wood


You could do string[] parts = string.Split(' '), and then extract by the index position parts[1] and parts [3] in your example.

like image 4
endian Avatar answered Nov 14 '22 06:11

endian


Yep. These are called "regular expressions". The one that will do the thing is

This (?<M0>.+) very (?<M1>.+)\.
like image 3
Anton Gogolev Avatar answered Nov 14 '22 08:11

Anton Gogolev