199

I have a task to match floating point numbers. I have written the following regular expression for it:

[-+]?[0-9]*\.?[0-9]*

But, it returns an error:

Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )

As per my knowledge, we need to use an escape character for the . also. Please correct me where I am wrong.

Emma
  • 27,428
  • 11
  • 44
  • 69
Gopal Samant
  • 2,109
  • 3
  • 15
  • 11
  • 13
    What language is this regex used in? – CaffGeek Sep 28 '12 at 15:34
  • 5
    @JDB - Why are you giving away 100 points for a number/float regex? The standard has always been `(?:\d+(?:\.\d*)?|\.\d+)` and has been posted ad infinitum on SO... –  Feb 22 '18 at 17:42
  • 1
    see also https://stackoverflow.com/questions/638565/parsing-scientific-notation-sensibly/658662#658662 – Jason S Feb 27 '18 at 04:24
  • 5
    `[-+]?([0-9]*[.])?[0-9]+([eE][-+]?\d+)?` if you want to catch exponential notation too, e,g, 3.023e-23 – wcochran Aug 02 '19 at 17:26
  • In some languages like Java or C++, the backslash must be escaped. So to get the regex "\.", you would use the string "\\.". Python gets around this by using raw strings. – HackerBoss Jan 10 '20 at 20:32
  • @user557597 - Why would the "standard" include non-capturing groups? That appears to me to be what those are: (?: ... ). Correct? And if it's been posted ad infinitum, why is it so difficult to find a non-specialized, generic numeric value regex on SO (using Google to search)? – GG2 May 04 '20 at 01:21

21 Answers21

435

TL;DR

Use [.] instead of \. and [0-9] instead of \d to avoid escaping issues in some languages (like Java).

Thanks to the nameless one for originally recognizing this.

One relatively simple pattern for matching a floating point number in a larger string is:

[+-]?([0-9]*[.])?[0-9]+

This will match:

  • 123
  • 123.456
  • .456

See a working example

If you also want to match 123. (a period with no decimal part), then you'll need a slightly longer expression:

[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)

See pkeller's answer for a fuller explanation of this pattern

If you want to include a wider spectrum of numbers, including scientific notation and non-decimal numbers such as hex and octal, see my answer to How do I identify if a string is a number?.

If you want to validate that an input is a number (rather than finding a number within the input), then you should surround the pattern with ^ and $, like so:

^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$

Irregular Regular Expressions

"Regular expressions", as implemented in most modern languages, APIs, frameworks, libraries, etc., are based on a concept developed in formal language theory. However, software engineers have added many extensions that take these implementations far beyond the formal definition. So, while most regular expression engines resemble one another, there is actually no standard. For this reason, a lot depends on what language, API, framework or library you are using.

(Incidentally, to help reduce confusion, many have taken to using "regex" or "regexp" to describe these enhanced matching languages. See Is a Regex the Same as a Regular Expression? at RexEgg.com for more information.)

That said, most regex engines (actually, all of them, as far as I know) would accept \.. Most likely, there's an issue with escaping.

The Trouble with Escaping

Some languages have built-in support for regexes, such as JavaScript. For those languages that don't, escaping can be a problem.

This is because you are basically coding in a language within a language. Java, for example, uses \ as an escape character within it's strings, so if you want to place a literal backslash character within a string, you must escape it:

// creates a single character string: "\"
String x = "\\";

However, regexes also use the \ character for escaping, so if you want to match a literal \ character, you must escape it for the regex engine, and then escape it again for Java:

// Creates a two-character string: "\\"
// When used as a regex pattern, will match a single character: "\"
String regexPattern = "\\\\";

In your case, you have probably not escaped the backslash character in the language you are programming in:

// will most likely result in an "Illegal escape character" error
String wrongPattern = "\.";
// will result in the string "\."
String correctPattern = "\\.";

All this escaping can get very confusing. If the language you are working with supports raw strings, then you should use those to cut down on the number of backslashes, but not all languages do (most notably: Java). Fortunately, there's an alternative that will work some of the time:

String correctPattern = "[.]";

For a regex engine, \. and [.] mean exactly the same thing. Note that this doesn't work in every case, like newline (\\n), open square bracket (\\[) and backslash (\\\\ or [\\]).

A Note about Matching Numbers

(Hint: It's harder than you think)

Matching a number is one of those things you'd think is quite easy with regex, but it's actually pretty tricky. Let's take a look at your approach, piece by piece:

[-+]?

Match an optional - or +

[0-9]*

Match 0 or more sequential digits

\.?

Match an optional .

[0-9]*

Match 0 or more sequential digits

First, we can clean up this expression a bit by using a character class shorthand for the digits (note that this is also susceptible to the escaping issue mentioned above):

[0-9] = \d

I'm going to use \d below, but keep in mind that it means the same thing as [0-9]. (Well, actually, in some engines \d will match digits from all scripts, so it'll match more than [0-9] will, but that's probably not significant in your case.)

Now, if you look at this carefully, you'll realize that every single part of your pattern is optional. This pattern can match a 0-length string; a string composed only of + or -; or, a string composed only of a .. This is probably not what you've intended.

To fix this, it's helpful to start by "anchoring" your regex with the bare-minimum required string, probably a single digit:

\d+

Now we want to add the decimal part, but it doesn't go where you think it might:

\d+\.?\d* /* This isn't quite correct. */

This will still match values like 123.. Worse, it's got a tinge of evil about it. The period is optional, meaning that you've got two repeated classes side-by-side (\d+ and \d*). This can actually be dangerous if used in just the wrong way, opening your system up to DoS attacks.

To fix this, rather than treating the period as optional, we need to treat it as required (to separate the repeated character classes) and instead make the entire decimal portion optional:

\d+(\.\d+)? /* Better. But... */

This is looking better now. We require a period between the first sequence of digits and the second, but there's a fatal flaw: we can't match .123 because a leading digit is now required.

This is actually pretty easy to fix. Instead of making the "decimal" portion of the number optional, we need to look at it as a sequence of characters: 1 or more numbers that may be prefixed by a . that may be prefixed by 0 or more numbers:

(\d*\.)?\d+

Now we just add the sign:

[+-]?(\d*\.)?\d+

Of course, those slashes are pretty annoying in Java, so we can substitute in our long-form character classes:

[+-]?([0-9]*[.])?[0-9]+

Matching versus Validating

This has come up in the comments a couple times, so I'm adding an addendum on matching versus validating.

The goal of matching is to find some content within the input (the "needle in a haystack"). The goal of validating is to ensure that the input is in an expected format.

Regexes, by their nature, only match text. Given some input, they will either find some matching text or they will not. However, by "snapping" an expression to the beginning and ending of the input with anchor tags (^ and $), we can ensure that no match is found unless the entire input matches the expression, effectively using regexes to validate.

The regex described above ([+-]?([0-9]*[.])?[0-9]+) will match one or more numbers within a target string. So given the input:

apple 1.34 pear 7.98 version 1.2.3.4

The regex will match 1.34, 7.98, 1.2, .3 and .4.

To validate that a given input is a number and nothing but a number, "snap" the expression to the start and end of the input by wrapping it in anchor tags:

^[+-]?([0-9]*[.])?[0-9]+$

This will only find a match if the entire input is a floating point number, and will not find a match if the input contains additional characters. So, given the input 1.2, a match will be found, but given apple 1.2 pear no matches will be found.

Note that some regex engines have a validate, isMatch or similar function, which essentially does what I've described automatically, returning true if a match is found and false if no match is found. Also keep in mind that some engines allow you to set flags which change the definition of ^ and $, matching the beginning/end of a line rather than the beginning/end of the entire input. This is typically not the default, but be on the lookout for these flags.

JDB
  • 25,172
  • 5
  • 72
  • 123
  • 2
    JDB, thanks and I hope you are still around! I'm reading your post in the future :) Your answer certainly takes care of 0.24 and 2.2 and correctly disallows 4.2.44 All tested with http://regex101.com/ However, it disallows 123. which as you say may be acceptable (and I think it is!). I can fix this by changing your expression to [-+]?(\d*[.])?\d* (notice * at end instead of +) but then crazy things like . (your second example) are allowed. Anyway to have my cake and eat it too? – Dave Mar 31 '14 at 23:17
  • 2
    @Dave - `\d+(\.\d*)?|\.\d+` – JDB Apr 01 '14 at 17:31
  • `/[-+]?(\d*[.])?\d+/.test("1.bc") // returns true` – yeouuu Feb 02 '16 at 20:05
  • 1
    @yeouuu yes, because `1.` matches. Add `^` and `$` to the beginning and end of the regex if you want to match only if the whole input matches. – JDB Feb 02 '16 at 20:16
  • 7
    floats can have exponents or be NaN/Inf, so i would use this: `[-+]?(([0-9]*[.]?[0-9]+([ed][-+]?[0-9]+)?)|(inf)|(nan))`, e/d for float/double precision float. Don't forget a fold case flag to the regex – Markus Schmassmann Sep 01 '16 at 09:12
  • Dont think this is entirely correct... it will match a version num kind of string, i.e. `10.30.90` – PradyJord Nov 10 '16 at 12:17
  • @prady It'll match part of it, given that I didn't use any boundaries (`^` and `$`). However, the period is not in a repetitive clause, so it can't match more than one `.`. – JDB Nov 10 '16 at 12:53
  • @prady To be clear, the regex will find a number within a larger string. In your example, my regex would match `10.30` and then `90` (if using `/g`), but separately. If you want to use this regex to validate that a given input is a number, then you must wrap it in anchors: `^[+-](\d*\.)?\d+$` – JDB Nov 10 '16 at 12:58
  • Although this answer has been accepted, I do not believe that it is correct. My suggestion is `[+-]?((\d+\.?\d*)|(\.\d+))`. See my answer elsewhere on this page for the reasoning – pkeller Mar 07 '17 at 18:14
  • 3
    I would recommend using a non-capturing group, as it us unlikely that someone aims at only capturing the integer part of the number. Like this: `[+-]?(?:[0-9]*[.])?[0-9]+`. Then, capturing the whole number is trivial. – Martin R. May 15 '17 at 09:41
  • Inn't it preferred to begin `[-+]` with `-` since `-` is also used for range? – wcochran Aug 02 '19 at 17:28
  • @wcochran - It may be in general, but isn't really that important in this case. – JDB Aug 02 '19 at 17:30
  • Probably be tolerant to white space `^\s*[+-]?(?:\d*\.)?\d+\s*$`. – Hans Ginzel Mar 10 '21 at 20:29
  • @HansGinzel - depends on context. There are too many variations to provide a single regex that will account for all use-cases. You'll need to modify to fit your unique circumstances. – JDB Mar 10 '21 at 22:22
  • Thanks @trevor, but I've got another answer, already linked in this answer, that covers a much wider variety of numbers and how to match them. The original question clearly only wanted to match simple integer and decimal numbers, so I'd rather keep this answer targeted on that most common use-case. – JDB Sep 03 '21 at 14:09
  • i see your answer has lots of links but i didn't see any link that looked like something that matches significant digits. what link in your answer is supposed to match significant digits? – Trevor Boyd Smith Sep 03 '21 at 15:59
  • @TrevorBoydSmith: "_If you want to include a wider spectrum of numbers, including scientific notation and non-decimal numbers such as hex and octal, see my answer to [How do I identify if a string is a number?](https://stackoverflow.com/a/16303109/211627)._" However, I did update the language to make clear that the answer includes scientific notation as well as hex and octal. – JDB Sep 03 '21 at 17:05
  • How would I go about matching anything that is NOT a number with possible decimal places? I don't want to match a float, or validate it, I want to sanitize anything from a string that is not a integer or a float. On another note, I don't know how you guys do regex, been trying to learn it for years and it is counter intuitive to me. Thanks @JDB! – Caio Mar Apr 11 '22 at 22:37
  • 1
    @CaioMars - As to learning regex, the gold standard is [Mastering Regular Expressions](https://www.oreilly.com/library/view/mastering-regular-expressions/0596528124/), by Jeffrey Friedl. As to your question... that's a new question that I can't really answer in the comments and which wouldn't fit my existing answer. You'll need to ask a new question, but you might want to search first... sounds like a question that might have already been answered elsewhere. – JDB Apr 12 '22 at 15:23
  • Thanks @JDB for your comment and recommendation, I appreciate it. I'm checking out the book now. As to the regex for, I thought maybe I could simply add a NOT somewhere to have it do what I wanted but it is not this simple. Anyway, thanks! – Caio Mar Apr 13 '22 at 18:03
  • what anyone wants is only a capture group that will match the whole number. This is not the case here. – sancelot Mar 15 '23 at 10:09
  • @sancelot - Sorry, if that's feedback or a request, then I don't understand what you are asking for. If you want a [capture group](http://www.rexegg.com/regex-capture.html), then just wrap the expression in parentheses. – JDB Mar 15 '23 at 13:03
  • @JDB, only one capture group for the whole floating field – sancelot Mar 15 '23 at 18:33
  • @sancelot - That wasn't a requirement of the original question, but if that's what you want then you can use non-capturing groups wrapped in a single capturing group. In JS, that would look like `([+-]?(?:[0-9]+(?:[.][0-9]*)?|[.][0-9]+))` (depending on your browser) – JDB Mar 15 '23 at 19:01
  • @sancelot - FWIW, non-capturing groups aren't really necessary in JS. For example: `"text -123.45 text".match(/[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)/g)[0]` will return `-123.45`. However, if you are working in a different language, then grouping might be more important to you. – JDB Mar 15 '23 at 19:09
40

I don't think that any of the answers on this page at the time of writing are correct (also many other suggestions elsewhere on SO are wrong too). The complication is that you have to match all of the following possibilities:

  • No decimal point (i.e. an integer value)
  • Digits both before and after the decimal point (e.g. 0.35 , 22.165)
  • Digits before the decimal point only (e.g. 0. , 1234.)
  • Digits after the decimal point only (e.g. .0 , .5678)

At the same time, you must ensure that there is at least one digit somewhere, i.e. the following are not allowed:

  • a decimal point on its own
  • a signed decimal point with no digits (i.e. +. or -.)
  • + or - on their own
  • an empty string

This seems tricky at first, but one way of finding inspiration is to look at the OpenJDK source for the java.lang.Double.valueOf(String) method (start at http://hg.openjdk.java.net/jdk8/jdk8/jdk, click "browse", navigate down /src/share/classes/java/lang/ and find the Double class). The long regex that this class contains caters for various possibilities that the OP probably didn't have in mind, but ignoring for simplicity the parts of it that deal with NaN, infinity, Hexadecimal notation and exponents, and using \d rather than the POSIX notation for a single digit, I can reduce the important parts of the regex for a signed floating point number with no exponent to:

[+-]?((\d+\.?\d*)|(\.\d+))

I don't think that there is a way of avoiding the (...)|(...) construction without allowing something that contains no digits, or forbidding one of the possibilities that has no digits before the decimal point or no digits after it.

Obviously in practice you will need to cater for trailing or preceding whitespace, either in the regex itself or in the code that uses it.

pkeller
  • 691
  • 6
  • 7
  • If you add the requirement to match numbers like `123.`, then yes... the or switch is the only solution, as I pointed out in [a comment](http://stackoverflow.com/questions/12643009/regular-expression-for-floating-point-numbers/12643073#comment34754539_12643073) on my original post. – JDB Mar 07 '17 at 18:30
  • I've edited my answer to include the alternate regex. The information about Java's regex is very interesting and good sleuthing. Thanks for that! (+1) I've linked to this answer from my post. – JDB Mar 07 '17 at 18:39
  • 2
    @JDB You are right, sorry for missing the version in your comment. My concern was that the regex that featured most prominently in the accepted answer wouldn't work for all cases. Thanks for linking to/including my suggestion. – pkeller Mar 09 '17 at 10:24
  • 2
    This, and all/most other answers, ignore that a float can have an exponent. – NateS Nov 08 '17 at 10:13
  • 1
    @NateS That's right, I did write "ignoring for simplicity the parts of it that deal with NaN, infinity, Hexadecimal notation and exponents", because that seems to match the scope of the OP's question. There are more complete implementations around, including the one that I found in the JDK source code. – pkeller Nov 09 '17 at 11:56
  • 2
    Can the regex `[+-]?((?=\.?\d)\d*\.?\d*)` be used to avoid the alternation? It uses a lookahead... – 4esn0k Sep 30 '19 at 19:53
  • 2
    @4esn0k Nice regex! I have played around with it, and it does work. I have two caveats: (1) not all regex engines support zero-width assertions (although most modern ones do, AFAIK), and (2) the look-ahead is just an alternation by another name: the engine still has to try something and backtrack if it doesn't work. Have an upvote for a very neat idea nevertheless. – pkeller Oct 24 '19 at 11:43
  • be aware that `[+-]?((\d+\.?\d*)|(\.\d+))` also matches incorrectly spaced numbers like "123.456.789.10111213" – Naveen Reddy Marthala Oct 12 '20 at 07:02
  • @NaveenKumar No it doesn't. It looks to me as if in your context you need to anchor the regex to the start and end of the line: ```echo 123.456.789 | perl -n -e '/^[+-]?((\d+\.?\d*)|(\.\d+))$/ or die "does not match"' does not match at -e line 1, <> line 1. ``` If you leave out the '^' and '$' then this snippet won't do a "die" of course, but that is because the regexp is only matching part of the input. – pkeller Oct 13 '20 at 10:18
30

I want to match what most languages consider valid numbers (integer and floats):

  • '5' / '-5'

  • '1.0' / '1.' / '.1' / '-1.' / '-.1'

  • '0.45326e+04', '666999e-05', '0.2e-3', '-33.e-1'

Notes:

  • preceding sign of number ('-' or '+') is optional

  • '-1.' and '-.1' are valid but '.' and '-.' are invalid

  • '.1e3' is valid, but '.e3' and 'e3' are invalid

In order to support both '1.' and '.1' we need an OR operator ('|') in order to make sure we exclude '.' from matching.

[+-]? +/- sing is optional since ? means 0 or 1 matches

( since we have 2 sub expressions we need to put them in parenthesis

\d+([.]\d*)?(e[+-]?\d+)? This is for numbers starting with a digit

| separates sub expressions

[.]\d+(e[+-]?\d+)? this is for numbers starting with '.'

) end of expressions

  • For numbers starting with '.'

[.] first character is dot (inside brackets or else it is a wildcard character)

\d+ one or more digits

(e[+-]?\d+)? this is an optional (0 or 1 matches due to ending '?') scientific notation

  • For numbers starting with a digit

\d+ one or more digits

([.]\d*)? optionally we can have a dot character an zero or more digits after it

(e[+-]?\d+)? this is an optional scientific notation

  • Scientific notation

e literal that specifies exponent

[+-]? optional exponent sign

\d+ one or more digits

All of those combined:

[+-]?(\d+([.]\d*)?(e[+-]?\d+)?|[.]\d+(e[+-]?\d+)?)

To accept E as well:

[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)

(Test cases)

saastn
  • 5,717
  • 8
  • 47
  • 78
Yannis T
  • 401
  • 4
  • 6
10

This is simple: you have used Java and you ought to use \\. instead of \. (search for character escaping in Java).

9

what you need is:

[\-\+]?[0-9]*(\.[0-9]+)?

I escaped the "+" and "-" sign and also grouped the decimal with its following digits since something like "1." is not a valid number.

The changes will allow you to match integers and floats. for example:

0
+1
-2.0
2.23442
DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70
  • The problem with this expression is that `.1` would not be permitted, even though such input is universally recognized as correct. – JDB Sep 28 '12 at 15:40
  • This will now accept zero length strings, `-` and `+`, which are not numbers. Regex is tricky! :) – JDB Sep 28 '12 at 15:43
  • Also, this doesn't answer the OP's actual question, which is that `\.` doesn't work. – JDB Sep 28 '12 at 15:48
5

Match strings which are considered valid representations of floating point values by C and C++ (and many other language) compilers, using the C++ regex library:

In C++ with #include <regex> you can do this:

std::regex r("[+-]?[0-9]+[.][0-9]*([e][+-]?[0-9]+)?");
return std::regex_match(value, r);

which is considerably more simple than most of the above C++ related answers.

It matches strings which are considered to be valid string representations of floating point numbers according to C++ compilers.

That means things like

1.
-1.

are considered valid representations of floating point numbers but that

.1
-.1

are not.

To explain the expression in more detail, it is essentially composed of two parts:

[+-]?[0-9]+[.][0-9]*([e][+-]?[0-9]+)?

[+-]?[0-9]+[.][0-9]*
and                 ([e][+-]?[0-9]+)?

The first part is easy to understand:

  • Optional (meaning 0 or 1 occurances of) '+' or '-' character
  • At least 1 digit, or more than one digit
  • A literal '.' character, which is mandatory (otherwise you have a representation of an integer not a floating point value)
  • If you want the '.' to be optional, change it to [.]?
  • Followed by zero or more digits

The second part is also quite easy once broken down.

  • Firstly note that the expression is contained in parenthesys, followed by a ?. This means the expression inside the parentesys must match 0 or 1 times. (Meaning it is optional.)
  • Inside we have a literal 'e' character which must match
  • Followed by an optional '+' or '-' character
  • Followed by 1 or more digits

The last part [+-]?[0-9]+ is a regex for matching an integer.

To match integer values as well use:

[+-]?[0-9]+[.]?[0-9]*([e][+-]?[0-9]+)?

Note the ? after the [.].

But be aware this will also match things like

+100e+100

which is perhaps an unusual representation of an integer. Although it is technically an integer, you probably wouldn't expect this to be a match.

Other answers provide a solution if you don't want this behaviour.

To ensure an entire string is a match rather than just a string containing a match use anchors:

"^[+-]?[0-9]+[.][0-9]*([e][+-]?[0-9]+)?$"

Examples

Without anchor characters

Without anchor characters

With anchor characters

enter image description here

With optional '.' character:

enter image description here

Note that this matches the string .-100 and .1e100 if you do not include the anchor characters, which may not be what you want.

When considering this problem:

My aim was to validate user input to ensure it matches a valid C++ string representation of a floating point number. Hence I am assuming you will use anchor characters and that you do not consider strings like

hello world 3.14 this contains a floating point number

to be a valid floating point number - because although the string contains a floating point number, the whole string is not a valid floating point number.

Other answers may suit your needs better if you just want to detect floating points within larger strings/text.

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225
  • This will fail to match "0E-10", an odd edge case I've run across while parsing JSON data. `[+-]?[0-9]+([.][0-9]+)?([e][+-]?[0-9]+)?` will match that and similar cases. – Gravis Mar 18 '23 at 21:14
  • @Gravis You need a version which matches `e` and `E` for the exponent. What you have is not an unusual edge case, but a format which doesn't match. – FreelanceConsultant Mar 19 '23 at 10:38
  • aww dang it! It was supposed to be `[eE]` in my comment. Also, the site backend that generated this value was Java which does use the uppercase 'E' for scientific notation per `String.valueOf()`! – Gravis Mar 20 '23 at 18:56
  • @Gravis That's weird, I would expect that to match. I've just put this into regex101 and it seems to be working? If you still find you can't get it working can you please post a new question **and send a link to me either by pasting the link here or sending it to my dm** – FreelanceConsultant Mar 21 '23 at 09:13
  • I see the problem now. Right above the "Examples" section you forgot to put `?` after `[.]`. – Gravis Mar 23 '23 at 01:10
  • @Gravis Ah that's actually an interesting point. Sorry I didn't pick up on that before. `10e10` isn't actually a valid floating point number format, at least according to a C/C++ dialect. It would require a floating point separator, for example: `10.e10`. However, as you have found there are other standards and formats in use. Indeed, many people would consider `0.` a bit of a weird format, although it is legal in C/C++. Most people probably expect `0.0` instead of `0.`. So yes, feel free to modify as you wish but be aware of the following point... – FreelanceConsultant Mar 23 '23 at 09:45
  • @Gravis The reason why the `.` is *not* optional is because `0` would be a valid floating point number. If if your case you do not need to distinguish between integers and floats, then there is no problem to make the `.` optional. – FreelanceConsultant Mar 23 '23 at 09:46
  • `0`, `1e+10`, and `-.1` are all valid floating-point literals in C++. You should take a look at this doc: https://en.cppreference.com/w/cpp/language/floating_literal Anyway, I ended up using a variant of Yannis_T's answer `[+-]?([[:digit:]]+[.][[:digit:]]*|[.]?[[:digit:]]+)([eE][+-]?[[:digit:]]+)?` which will match all base 10 floating point values sans precision marker. – Gravis Mar 23 '23 at 21:50
  • @Gravis Ok I didn't realize that. I will probably adjust this answer at some point to add info about that – FreelanceConsultant Mar 24 '23 at 18:58
4

This one worked for me:

(?P<value>[-+]*\d+\.\d+|[-+]*\d+)

You can also use this one (without named parameter):

([-+]*\d+\.\d+|[-+]*\d+)

Use some online regex tester to test it (e.g. regex101 )

grafi71
  • 379
  • 2
  • 5
2
^[+-]?([0-9]{1,})[.,]([0-9]{1,})$

This will match:

  1. 1.2
  2. 12.3
  3. 123.4
  4. 1,2
  5. 12,3
  6. 123,4
Mihai Ciobanu
  • 421
  • 4
  • 6
1

for javascript

const test = new RegExp('^[+]?([0-9]{0,})*[.]?([0-9]{0,2})?$','g');

Which would work for 1.23 1234.22 0 0.12 12

You can change the parts in the {} to get different results in decimal length and front of the decimal as well. This is used in inputs for entering in number and checking every input as you type only allowing what passes.

mjwrazor
  • 1,866
  • 2
  • 26
  • 42
1

This captures floating-point numbers as recognized in C/C++ code:

[+-]?((((\d+\.?\d*)|(\.\d+))([eE][+-]?\d+[fF]?)?)|((\d+\.\d*)|(\.\d+))[fF]?)
  • +/- sign
  • either only digits, digits., .digits or digits.digits
  • optional exponent with e or E, +/- sign and digits
  • optional f or F at the end, but only if the number contains a . or an exponent
ProjectPhysX
  • 4,535
  • 2
  • 14
  • 34
1
(\d*)(\.)*(\d+)

This would parse the below.

11.00
12
.0

There must be one number. The decimal point and the number before the decimal point is optional.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
user641247
  • 35
  • 6
0
[+-]?(([1-9][0-9]*)|(0))([.,][0-9]+)?

[+-]? - optional leading sign

(([1-9][0-9]*)|(0)) - integer without leading zero, including single zero

([.,][0-9]+)? - optional fractional part

Aleksei Gutikov
  • 343
  • 4
  • 10
  • 1
    Give more info - for people not knowing the regexps it is hyerogliphs. For people knowing them, they don't need it. – peterh Nov 11 '15 at 10:42
0
[+/-] [0-9]*.[0-9]+

Try this solution.

Martin Benninger
  • 597
  • 5
  • 13
0

In C++ using the regex library

The answer would go about like this:

[0-9]?([0-9]*[.])?[0-9]+

Notice that I don't take the sign symbol, if you wanted it with the sign symbol it would go about this:

[+-]?([0-9]*[.])?[0-9]+

This also separates a regular number or a decimal number.

Emma
  • 27,428
  • 11
  • 44
  • 69
LuisDev99
  • 1,697
  • 17
  • 13
0

In c notation, float number can occur in following shapes:

  1. 123
  2. 123.
  3. 123.24
  4. .24
  5. 2e-2 = 2 * 10 pow -2 = 2 * 0.1
  6. 4E+4 = 4 * 10 pow 4 = 4 * 10 000

For creating float regular expresion, I will first create "int regular expresion variable":

(([1-9][0-9]*)|0) will be int

Now, I will write small chunks of float regular expresion - solution is to concat those chunks with or simbol "|".

Chunks:

- (([+-]?{int}) satysfies case 1
- (([+-]?{int})"."[0-9]*)  satysfies cases 2 and 3
- ("."[0-9]*) satysfies case 4
- ([+-]?{int}[eE][+-]?{int}) satysfies cases 5 and 6

Final solution (concanating small chunks):

(([+-]?{int})|(([+-]?{int})"."[0-9]*)|("."[0-9]*)|([+-]?{int}[eE][+-]?{int})
0

For those who searching a regex which would validate an entire input that should be a signed float point number on every single character typed by a user.

I.e. a sign goes first (should match and be valid), then all the digits (still match and valid) and its optional decimal part.

In JS, we use onkeydown/oninput event to do that + the following regex:

^[+-]?[0-9]*([\.][0-9]*)?$
sergredov
  • 11
  • 1
0

In C Language, the answer would go about like this:

[+-]?((\d+\.?\d*)|(\.\d+))(([eE][+-]?)?\d+)?[fFlL]?
wei He
  • 1
0

If we are only looking to identify the floating points and not the integers, then can use this:

'\d*\.\d+'
0

I would suggest this pattern [-+]?[0-9]+[.]?[0-9]*

M--
  • 25,431
  • 8
  • 61
  • 93
-1

This is for javascript (idk if there's a large difference between languages)

`int: /0|[1-9][0-9]*/`

For floats:

`float:   /[0-9]+\.[0-9]+/`
-2

if you are using flutter you can use [0-9]([.]([0-9])*)? This would parse 123.123