正则表达式用于多个数字输入

时间:2018-10-13 08:20:57

标签: java regex

对此我还比较陌生,但是我试图做一个正则表达式,该正则表达式的格式是1-1000范围内的多个数字,例如:1 200 300 2 245

<center>
<div class ="form">
		<h2> Sales Tax Calculator</h2>
		<form name="orderform" id="orderform">
		<table>
</div>
  <tr><th>
   <label>Product: </label>
  </th>
  <th scope="row">
   <div align="left">
    <label><span>$</span></label>
    <input name="price" type="text" id="price" size="10">
   </div>
  </th>

  
  <tr><th>
   <label>Quantity</label>
  </th>
  <th scope="row">
   <div align="left">
    <label><span>#</span></label>
    <input name="quantity" type="text" id="quantity" size="10">
     
   </div>
  </th>
 
  <tr><th>
   <label>Subtotal:</label>
  </th>
  <th scope="row">   
   <div align="left">
    <label>$</label>
    <input name="subtotal" type="text" id="subtotal" onFocus="this.form.elements[1].focus()" size="10"> &nbsp;&nbsp;
    <input name="subBtn" onClick="subTotal();" type="button" id="subBtn" value="Subtotal">
   </div>
  </th>
 </tr>
  
   <tr><th>
   <label>Tax:</label>
  </th>
   <th scope="row">
   <div align="left">
    <label>$</label>
     <input name="salestax" type="text" id="salestax" onFocus="this.form.elements[1].focus()" size="10"> &nbsp;&nbsp;               
     <input name="taxBtn" onClick="calculateTax();" type="button" id="taxBtn" value="Tax">  
   </div>
  </th>
 </tr>
 
  <tr><th>
   <label>Total:</label>
  </th>
  <th scope="row">
   <div align="left">
    <label>$</label>
    <input name="gtotal" type="text" id="gtotal" onFocus="this.form.elements[2].focus()" size="10"> &nbsp;&nbsp;
    <input name="gtotalBtn" onClick="grandTotal();" type="button" id="gtotalBtn" value="Calculate Order">
   </div>
  </th>
 </tr>
</table>
</form>      
</div>
</center>

但是我在上面所做的事情似乎没有用,我只是想知道它是否正确。如果是这样,那么问题可能出在我的代码的其他部分。

2 个答案:

答案 0 :(得分:1)

^[1-9][0-9]{0,2}$|^1000$

^ - starts with
[1-9] - first char [1-9]
[0-9]{0,2} - then 0-2 chars [0-9]
$- ends with 
^[1-9][0-9]{0,2}$ - numbers ranging from 1-999
|^1000$ - or 1000

答案 1 :(得分:1)

您必须使用量词来允许多个数字:

^(?:[1-9][0-9]{0,2}|1000)(?: +(?:[1-9][0-9]{0,2}|1000))*$

DEMO

说明:

^                                   : beginning of the string
    (?:                             : start non capture group
        [1-9][0-9]{0,2}             : 1 digit from 1 to 9, followed by optional 1 or 2 digits (i.e. from 1 to 999)
      |                             : OR
        1000                        : 1000
    )                               : end group
    (?:                             : start non capture group
         +                          : 1 or more spaces
        (?:[1-9][0-9]{0,2}|1000)    : same as above
    )*                              : group may appear 0 or more times
$                                   : end of string