How to extract number string based on specific code

JimiJ13
JimiJ13 used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
string subjectString = "wwww bs | stk: 15 Cost: 66.1";
try {
	Regex regexObj = new Regex(@"stk: (\d+\.*\d*) Cost: (\d+\.*\d*)");
	stk = regexObj.Match(subjectString).Groups[1].Value;
        cost = regexObj.Match(subjectString).Groups[2].Value;
} catch (ArgumentException ex) {
	// Syntax error in the regular expression
}

Open in new window

HTH,
Dan
Top Expert 2016

Commented:
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
JimiJ13I T Consultant

Author

Commented:
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.
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

JimiJ13I T Consultant

Author

Commented:
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.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
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
JimiJ13I T Consultant

Author

Commented:
Julian Hansen (JulianH),

Thanks. But your suggestion gave empty result.
JimiJ13I T Consultant

Author

Commented:
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
}

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial