How to limit the number of houses before the comma in a regular expression?

Asked

Viewed 1,159 times

2

I am using this expression to not let the user type point before any number and limiting 2 houses after the comma, but I also needed to limit 5 houses before the comma, the way it is I can enter as many numbers as you want before the comma. Does anyone know how I can do that? I’m getting beat up here.

My expression: "([0-9]+(\\.)?([0-9]?[0-9]?))"

  • 1

    Kind of? \d{1,5}(\.\d{1,2})? (1 to 5 digits, and optionally the dot followed by 1 or 2 digits) P.S. These groups are capture? Or whatever?

2 answers

2

The same way you did to limit later:

"([0-9][0-9]?[0-9]?[0-9]?[0-9]?(\\.)?([0-9]?[0-9]?))"

That is, the first is mandatory, and the following 4 are optional. However, I have some suggestions to improve this regex:

  1. Use the keys to choose the number of times an element will repeat itself. exp{n} means that the expression needs to occur exactly n times. exp{a,b} means it needs to occur at least a and at most b times:

    "([0-9]{1,5}(\\.)?([0-9]{0,2}))"
    
  2. If these groups are not capture, I suggest removing them as this complicates unnecessarily the regex:

    "[0-9]{1,5}\\.?[0-9]{0,2}"
    
  3. This way it is still possible to have a point without any digit on the front, or no point and two digits more. Connect the dot to the digits, and require at least 1 digit if the dot is present:

    "[0-9]{1,5}(\\.[0-9]{1,2})?"
    
  4. You can use \d (escaped, \\d) to represent a digit instead of the interval [0-9]:

    "\\d{1,5}(\\.\\d{1,2})?"
    
  5. If you want to avoid left zeros, separate the case from the 0 with the case of [1-9] followed by 0 to 4 digits:

    "(0|([1-9]\\d{0,4}))(\\.\\d{1,2})?"
    
  • vlw by the answer, but none worked. What happens is that these expressions let me put if I have typed up to 5 numbers. They accept more than 5 numbers, and after 6° number no longer lets me type point.

  • @daniel12345smith The problem should be in the way you are using then, not in the expression itself. Because the expressions are correct, see that example. If you need more help, show the Java code where you use this expression.

0

I imagine this one might satisfy you: /^(\d{1,5})?(\.\d{1,2})?$/

Here dry an example on HTML of validation:

$('input').keyup(function(e){
  var val = this.value;
  var test = /^(\d{1,5})?(\.\d{1,2})?$/
  
  if(test.test(val)){
    $("p").html("Válido.")
  }else{
    $("p").html("Inválido.")
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="12345.67"/><br>
<p></p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.