0

Looking for a regex to get the number from a string.

My string could be:

abcd1
abcd01
abcd11

I tried this but it is not working: /\d+$/ and some others but they are not seems to be correct.

Is there any easy way to get the number from a string? ANd it will be at the end.

1
  • Why the slashes at the beginning and the end? C# is not JavaScript. Commented Dec 7, 2012 at 17:00

2 Answers 2

4

I believe you want this regex (without the beginning slashes as C# does not need that)

\d+$

To ignore leading 0

[1-9]\d*$

If you want to drop ALL leading 0's, it honestly would be easier to just cast your result to an Int32

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

5 Comments

I just tested and it is giving me the result except for this abcd01. Is there anyway to just get 1 instead of 01?
@alice7 use (0|[1-9]\d*)$ then
Hamlet is ALMOST right if you want to ignore the leading 0's: [1-9]\d*$
@alice7 do you just want to drop leading zeros, or do you only want the last number? In your example above of abcd11 do you want 1 or 11?
@Esailija: thanks it works. I tested with all the above and it works.
3

I think it is that you want. "Is there anyway to just get 1 instead of 01?" Yes, there is.

[1-9]\d*$

2 Comments

Your answer will force two digits, change the + to a * and this will work
@Esailija You are right, that will only catch one leading 0. I updated my answer

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.