Kiran
Kiran

Reputation: 8538

get measurement value only from string

I have a string which gives the measurement followed the units in either cm, m or inches.

For example :

The number could be 112cm, 1.12m, 45inches or 45in.

I would like to extract only the number part of the string. Any idea how to use the units as the delimiters to extract the number ?

While I am at it, I would like to ignore the case of the units.

Thanks

Upvotes: 2

Views: 1257

Answers (6)

DP.
DP.

Reputation: 51

Try using regular expression \d+ to find an integer number.

resultString = Regex.Match(measurementunit , @"\d+").Value;

Upvotes: 1

NeverHopeless
NeverHopeless

Reputation: 11233

Using Regex this can help you out:

(?i)(\d+(?:\.\d+)?)(?=c?m|in(?:ch(?:es)?)?)

Break up:

 (?i)                 = ignores characters case // specify it in C#, live do not have it
 \d+(\.\d+)?          = supports numbers like 2, 2.25 etc
 (?=c?m|in(ch(es)?)?) = positive lookahead, check units after the number if they are 
                        m, cm,in,inch,inches, it allows otherwise it is not.
 ?:                   = specifies that the group will not capture
 ?                    = specifies the preceding character or group is optional

Demo

EDIT

Sample code:

MatchCollection mcol = Regex.Matches(sampleStr,@"(?i)(\d+(?:\.\d+)?)(?=c?m|in(?:ch(?:es)?)?)")

foreach(Match m in mcol)
{
    Debug.Print(m.ToString());   // see output window
}

Upvotes: 2

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15158

You can try:

string numberMatch = Regex.Match(measurement, @"\d+\.?\d*").Value;

EDIT

Furthermore, converting this to a double is trivial:

double result;
if (double.TryParse(number, out result))
{
    // Yeiiii I've got myself a double ...
}

Upvotes: 2

apptimal
apptimal

Reputation: 494

I guess I'd try to replace with "" every character that is not number or ".":

//s is the string you need to convert
string tmp=s;
foreach (char c in s.ToCharArray())
            {
                if (!(c >= '0' && c <= '9') && !(c =='.'))
                    tmp = tmp.Replace(c.ToString(), "");
            }
s=tmp;

Upvotes: 1

KTHL
KTHL

Reputation: 119

Is it a requirement that you use the unit as the delimiter? If not, you could extract the number using regex (see Find and extract a number from a string).

Upvotes: 0

Marko Juvančič
Marko Juvančič

Reputation: 5890

Use String.Split http://msdn.microsoft.com/en-us/library/tabh47cf.aspx

Something like:

var units = new[] {"cm", "inches", "in", "m"};
var splitnumber = mynumberstring.Split(units, StringSplitOptions.RemoveEmptyEntries);
var number = Convert.ToInt32(splitnumber[0]);

Upvotes: 2

Related Questions