0

I thought I had it with [0-9] but when I ran it that only took one number.

The string goes for example:

1 note
1,234 notes
68,000 notes

I want it so it takes the whole number and leaves out the notes part and the spaces and also the comma so just the full number.

The [0-9] would only take the first number of the string even when there wasnt a comma.

So how to only take the number please?

1
  • you mean this? \d+(?:,\d+)* ? Commented Aug 30, 2015 at 13:42

1 Answer 1

1

[0-9] means any one character between 0 and 9. What you are looking for is these characters repeated any number of times, but no other character should be there. The correct way to write this is [0-9]+.

M+, where M is some regex rule is equivalent to M M*, where * means 0 or more occurrences. So M+ can be inferred as at least one occurrence of portions specified by M.

EDIT: The question now also states that the entire number should be read, but the comma should be excluded from the output. AFAIK, this is impossible to be done using only regex, as the matched text can't be different from the stored text. A possible solution is to add , to the list of allowed characters and parse the result to remove them later on.

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

3 Comments

Ok, cool that got a number less than 1000. But how would the regex look to get the numebr when theres a comma in it like 1,234? since I just tried for 19,000 and it only got 19. Yes no biggy to only get the number with comma included since I can do a replace after.
@programminglearner Adding , to the list of allowed characters should work. So [0-9,] should work. Note that this will match additional numbers such as 23,,52,2,1. You should ask yourself if such cases can occur. If needed, refine the regex more to limit its expressiveness.
EDIT: Ok i got it :): [0-9]+,[0-9]+ Thanks for the info. EDIT: ah I see your way is more compact :) so used that. Cheers.

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.