0

I have a string

"transform(23, 45)"

from this string i have to extract 23 and 45, i did

var xy = "transform(23,45)".Substring("transform(23,45)".indexOf('(') + 1).TrimEnd(')');
var num = xy.Split(',');

I am using c#. Is there any better method to do this in c#?

4 Answers 4

6

Use a Regular Expression:

string sInput = "transform(23, 45)";
Match match = Regex.Match(sInput, @"(\d)+",
              RegexOptions.IgnoreCase);

if (match.Success)
{
    foreach (var sVal in match)
             // Do something with sVal
}

You can read more on Regular Expressions here. Use RegExr for training, it helps alot!

Sign up to request clarification or add additional context in comments.

Comments

2

Well, a simply regular expression string would be ([0-9]+), but you may need to define other expression constraints, e.g., what are you doing to handle periods, commas, etc in strings?

var matches = Regex.Matches("transform(23,45)", "([0-9]+)");
foreach (Match match in matches)
{  
    int value = int.Parse(match.Groups[1].Value);
    // Do work.
}

1 Comment

+1 for "periods, commas, etc...", and to add to the list: non-10-base number literals, forced type literals (VB examples, but other programming languages have them as well), etc.
0

This will do it

string[] t = "transform(23, 45)".ToLower().Replace("transform(", string.Empty).Replace(")", string.Empty).Split(',');

Comments

0

Use Regex:

var matches = Regex.Matches(inputString, @"(\d+)");

explain:

\d    Matches any decimal digit.

\d+   Matches digits (0-9) 
      (1 or more times, matching the most amount possible) 

and for using:

foreach (Match match in matches)
{  
    var number = match.Groups[1].Value;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.