Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for validating only numbers and dots

Tags:

java

regex

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.

like image 389
Srinivas B Avatar asked Aug 17 '12 06:08

Srinivas B


People also ask

What is the regex for only numbers?

The \d is used to express single number in regex. The number can be any number which is a single number. The \d can be used to match single number. Alternatively the [0-9] can be used to match single number in a regular expression.

Can you use regex with numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


4 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+)*$");
like image 95
Viliam Búr Avatar answered Nov 12 '22 05:11

Viliam Búr


<!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>
like image 20
Narasimha Avatar answered Nov 12 '22 06:11

Narasimha


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.

like image 39
Jon Lin Avatar answered Nov 12 '22 05:11

Jon Lin


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
like image 21
Vinu Vish Avatar answered Nov 12 '22 05:11

Vinu Vish