2

How can I take only the number from strings in this format:

       "####-somestring"
       "###-someotherstring"
       "######-anotherstring"
2
  • check the MaskedTextBox control en.csharp-online.net/MaskedTextBox Commented Feb 16, 2010 at 20:46
  • you can still copy & paste non allowed characters into the textbox without additional validating, so you can just take a normal textbox and validate it yourself. Also, there is no mention of a control in the question. Commented Feb 16, 2010 at 20:49

5 Answers 5

10
int.parse( Regex.match(String, @"\d+").value)
Sign up to request clarification or add additional context in comments.

2 Comments

Of course, you'd need a closing ", but this gets my upvote. You'd need to account for no-match situations too.
\d would do it just habit. you don't need the () since i'm not using a capture or a group
3
string s =  "####-somestring";
string digits = s.Substring(0, s.IndexOf("-") - 1);
int parsedDigits = int.Parse(digits);

for more complicated combinations you'd have to use Regex.

Comments

2

if you are sure they will always have a '-' in them you can use the string split function.

string cutThisUp = "######-anotherstring";
string[] parts = cutThisUp.Split(Convert.ToChar("-"));
int numberPart = Convert.ToInt32(parts[0]);

1 Comment

Just FYI, You don't need to call Convert.ToChar("-"); use single quotes to indicate a char rather than a string (so: cutThisUp.Split('-')).
1

You could use something like the following:

string s = "####-somestring";
return Regex.Match(s, "(\d)+").Value);

Comments

1

Yet another option: split on the - character and try to parse the first item in the resulting array (this is the same as nbushnell's suggestion, with a little added safety):

public bool TryGetNumberFromString(string s, out int number) {
    number = default(int);

    string[] split = s.Split('-');
    if (split.Length < 1)
        return false;

    return int.TryParse(split[0], out number);
}

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.