4

Anyone keen to show me how to get the integer part from this string using c#?

string url = "/{localLink:1301}";

I've been into using something like this but didn't get it to work properly

var getNumeric = new Regex(".*([0-9]+)");
1
  • 2
    Please show the whole of what you tried, and the results you got. Read tinyurl.com/so-hints Commented Nov 6, 2011 at 13:33

3 Answers 3

11

Your expression could be as simple as \d+, given the assumption that there will be only one number in your input. Still under that assumption, using ToString on the resulting Match will give you what you are looking for.

var regex = Regex.Match("/{localLink:1301}", @"\d+");
var result = regex.ToString();
Sign up to request clarification or add additional context in comments.

Comments

2

Your .* is greedy. you either need .*? or [^\d]*

new Regex( ".*?(\d+)" );

2 Comments

Why shouldn't the match be greedy? You want to capture all of the numbers, not just the first one.
@vcjones, you want the numeric part to be greedy, not the part leading up to the numeric part. the .* before the [0-9]+ was matching the first 3 numeric digits since . matches any character.
1

you can try this....

string output = new string(input.ToCharArray().Where(c => char.IsDigit(c)).ToArray());

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.