Regex for Validating Only Numbers and Dots

I want a java regex expression that accepts only the numbers and dots.

for example,

             1.1.1 ----valid
             1.1   ----valid
             1.1.1.1---valid
             1.    ----not valid

The dots should not be at the starting position or at the ending position.

0

5 Answers

I guess this is what you want:

^\d+(\.\d+)*$

Explanation: It accepts numbers separated by dots; it starts and ends with number; a number can have multiple digits; one number without dots is also accepted.

Variant without multiple digits:

^\d(\.\d)*$

Variants where at least one dot is required:

^\d+(\.\d+)+$
^\d(\.\d)+$

Don't forget that in Java you have to escape the \ symbols, so the code will look like this:

Pattern NUMBERS_WITH_DOTS = Pattern.compile("^\\d+(\\.\\d+)*$");
3

So you want a regex that wants numbers and periods but starts and ends with a number?

"[0-9][0-9.]*[0-9]"

But this isn't going to match things like 1. which doesn't have any periods, but does start and end with a number.

2

I guess this is what you want:

Pattern.compile("(([0-9](\\.[0-9]*))?){1,13}(\\.[0-9]*)?(\\.[0-9]*)?(\\.[0-9]*)?", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL | Pattern.MULTILINE);

Explanation: It accepts numbers separated by dots; it starts and ends with number; a number can have multiple digits; one number without dots is not accepted.

The output like this--

  • 1.1
  • 1.12
  • 1.1.5
  • 1.15.1.4
<!DOCTYPE html>
<html>
<body>

<p>RegEx to allow digits and dot</p>
Number: <input type="text" id="fname" onkeyup="myFunction()">

<script>
function myFunction() {
    var x = document.getElementById("fname");
    x.value = x.value.replace(/[^0-9\.]/g,"");
}
</script>

</body>
</html>
"^\\d(\\.\\d)*$"

1     ----valid (if it must be not valid, replace `*` => `+` )
1.1.1 ----valid
1.1   ----valid
1.1.1.1---valid
1.    ----not valid
11.1.1 ---not valid (if it must be valid, add `+` after each `d`) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest