jason
jason

Reputation: 7174

How to get two numerical values from a string in C#

I have a string like this :

X LIMITED COMPANY (52100000/58447000)

I want to extract X LIMITED COMPANY, 52100000 and 58447000 seperately.

I'm extracting X LIMITED COMPANY like this :

companyName = Regex.Match(mystring4, @"[a-zA-Z\s]+").Value.Trim(); 

But I'm stuck with extracting numbers, they can be 1, 2 or large numbers in the example. Can you show me how to extract those numbers? Thanks.

Upvotes: 1

Views: 70

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186843

Try regular expressions with alternative | (or):

  • Either word symbols (but not digits) [\w-[\d]][\w\s-[\d]]+)
  • Digits only ([0-9]+)

E.g.

string mystring4 = @"AKASYA CAM SANAYİ VE TİCARET LİMİTED ŞİRKETİ(52100000 / 58447000)";

string[] values = Regex
  .Matches(mystring4, @"([\w-[\d]][\w\s-[\d]]+)|([0-9]+)")
  .OfType<Match>()
  .Select(match => match.Value.Trim())
  .ToArray(); 

Test

// X LIMITED COMPANY
// 52100000
// 58447000  
Console.Write(string.Join(Environment.NewLine, values)); 

I suggested changing the initial pattern [a-zA-Z\s]+ into [a-zA-Z][a-zA-Z\s]+ in order to skip matches which contain separators only (e.g. " ")

Upvotes: 1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56747

If the format is fixed, you could try this:

var regex = new Regex(@"^(?<name>[^\(]+)\((?<n1>\d+)/(?<n2>\d+)\)");

var match = regex.Match(input);
var companyName = match.Groups["name"].Value;
var number1 = Convert.ToInt64(match.Groups["n1"].Value);
var number2 = Convert.ToInt64(match.Groups["n2"].Value);

This matches everything up to the open parentheses and puts it into a named group "name". Then it matches two numbers within parentheses, separated by "/" and puts them into groups named "n1" and "n2" respectively.

Upvotes: 0

Try using named groups:

var s = "X LIMITED COMPANY (52100000 / 58447000)";
var regex = new Regex(@"(?<CompanyName>[^\(]+)\((?<Num1>\d+)\s*/\s*(?<Num2>\d+)\)");

var match = regex.Match(s);
var companyName = match.Groups["CompanyName"];

Upvotes: 1

Related Questions