Avatar of JimiJ13
JimiJ13
Flag 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.
C#Regular Expressions

Avatar of undefined
Last Comment
JimiJ13

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Dan Craciun

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
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
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.
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.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Julian Hansen

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
JimiJ13

ASKER
Julian Hansen (JulianH),

Thanks. But your suggestion gave empty result.
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
}
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.