Link to home
Start Free TrialLog in
Avatar of JimiJ13
JimiJ13Flag for Philippines

asked on

How to extract number string based on specific code

Dear Experts,

I have this generic string:
wwww bs | stk: 15 Cost: 66.1

How can I extract the  stk & cost based on the above string?


Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Dan Craciun
Dan Craciun
Flag of Romania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rgonzo1971
Rgonzo1971

HI,

why not use split

      var names = "wwww bs | stk: 15 Cost: 66.1".Split(' ');
      var stk = names.GetValue(4);
      var Cost = names.GetValue(6);

Open in new window

Regards
Avatar of JimiJ13

ASKER

Dan Craciun,
I tried your suggestion and these are the errors:

2 The name 'stk' does not exist in the current context      
2 The name 'cost' does not exist in the current context      

Any idea?

Thanks.
Avatar of JimiJ13

ASKER

Rgonzo1971,

When I tried it in the following strings and it did not work:

"The best bs | stk: 15 Cost: 66.1".Split(' ');
"Thebestbs | stk: 15 Cost: 66.1".Split(' ');
"The best is yet | stk: 15 Cost: 66.1".Split(' ');

Thanks.
A slightly updated RegEx
stk:\s*(\d+\.?\d*)\s*cost:\s*(\d+\.?\d*)

Open in new window

Allows for variable spaces between elements and will match a single decimal only
Avatar of JimiJ13

ASKER

Julian Hansen (JulianH),

Thanks. But your suggestion gave empty result.
Avatar of JimiJ13

ASKER

Great! it works with minor modification:

string subjectString = "wwww bs | stk: 15 Cost: 66.1";
try {
      Regex regexObj = new Regex(@"stk: (\d+\.*\d*) Cost: (\d+\.*\d*)");
      string stk = regexObj.Match(subjectString).Groups[1].Value;
        string cost = regexObj.Match(subjectString).Groups[2].Value;
} catch (ArgumentException ex) {
      // Syntax error in the regular expression
}