Obviously, this is a massive, complicated, nigh-unreadable regex. The numbers you're looking for will be in capture group 1. Basic patternĬonsidering the examples you've given, here's a simple regex that allows pretty much any integer or decimal in 0000 format and blocks everything else: ^\d*\.?\d+$ If that's not an option for you, keep reading. What you should really do is split the whole thing on whitespace, then run two or three smaller regexes on the results. A single regex for two different number formats is hard to maintain even when they aren't embedded in other text. is a wrong answer.įirst of all, if you don't need to do this all in one regex, don't. IMHO anything that fails to pull 1,234.- and only those numbers-out of abc22 1,234.56 9.9.9. That's simple enough to fix, even if the numbers are embedded in other text. This is a very common task, but all the answers I see here so far will accept inputs that don't match your number format, such as ,111, 9,9,9, or even.
![regex for number and decimal regex for number and decimal](https://i.pinimg.com/originals/cd/fe/15/cdfe1540c16d493121ce4a43656e5889.jpg)
![regex for number and decimal regex for number and decimal](https://content.breatheco.de/static/ae425479a8857181ef8dbee4f6e6651f/0a47e/39f93d0d-248e-4e94-b402-b744c4b06a4d.png)
Now that that's out of the way, most of the following is meant as commentary on how complex regex can get if you try to be clever with it, and why you should seek alternatives. #Commas optional as long as they're consistent #For numbers embedded in sentences, see discussion below
![regex for number and decimal regex for number and decimal](https://regexland.com/wp-content/uploads/2020/11/regex-decimal-numbers-300x157.png)
EDIT: Since this has gotten a lot of views, let me start by giving everybody what they Googled for: #ALL THESE REQUIRE THE WHOLE STRING TO BE A NUMBER