Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi everyone,

Can someone help me write a C# regular expression to extract "2.224 KB" from the following string @{AnyText=2.224 KB (2,277 bytes)

Regards
Sebastian
Posted
Updated 17-Jan-13 23:06pm
v2

How about:
C#
...
string input = ...;
Match match = Regex.Match(input, @"\w+\s*=\s*(\d+(?:\.\d+)?\s*[A-Z]+)");
string size = match.Success ? match.Groups[1].Value : string.Empty;
...

Depends very much on the input string if the @ and { are relevant to properly match the text.

Note: If you need to be culture aware, the whole regex becomes far more difficult: decimal separator and thousand separator may be rather "weird" in versious cultures (e.g. some scandinavian language, the thousand separator is some kind of space...). In that case, you need to be a bit more fuzzy, e.g. @"\w+\s*=\s*(.*?\s*[A-Z][A-Z])".

Cheers
Andi
 
Share this answer
 
Comments
Sebastian T Xavier 28-Jan-13 0:27am    
good answer
More information is required before this can be answered appropriately.

Assumptions:
1. String always remains like: "@{AnyText=< SizeInKBHere > (2,277 bytes)"
2. This is the total string and not a part of a huge string.

You can get substring from the string provided.
1. Get the index of "=" and second space.
2. Using information from #1, get the substring starting after "=" till second space.
 
Share this answer
 
v2
Comments
Sebastian T Xavier 18-Jan-13 5:11am    
string is not same always, see the updated question. this is the whole string.
dan!sh 18-Jan-13 5:14am    
My response still stays valid assuming "AnyText" will not have "=" sign.
Sebastian T Xavier 18-Jan-13 5:22am    
I can try the following code, but looking for a better approach...

String stra = "@{TotalItemSize=2.224 KB (2,277 bytes)";
int startindex = 0;
int endindex = 0;
string result = "";
startindex = stra.IndexOf("=")+1;
endindex = stra.IndexOf(" (");
result = stra.Substring(startindex, endindex-startindex );

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900