I want a java regex expression that accepts only the numbers and dots.
for example,
1.1.1 ----valid
1.1 ----valid
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--
<!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:
^\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+)*$");
"^\\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`)