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.
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.
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.
$ means "Match the end of the string" (the position after the last character in the string).
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+)*$");
<!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>
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.
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--
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With