简体   繁体   中英

Regular Expression - 4 digits, with optional 1 or 2 decimal places

Have a regular expression issue that I can't seem to quite get.

Requirements: - Value between 0-9999 - Optionally can add either one or two decimals ( eg, 0.01 - 9999.99)

I've got a regex test and it looks to pass but when using it in my SAPUI5 app it doesn't seem to be working.

https://regex101.com/r/kB7oJ2/13

JS code:

var iQuantity = parseFloat(oArticle._Quantity);
var regexp = new RegExp('^([0-9]{1,4})(\.[0-9]{1,2})?$').test(iQuantity);

console.log(iQuantity);
console.log(regexp);

if (regexp === false) {
     return this.setItemToError(oInput, oArticle, 
     this.getResourceBundle().getText("regExp"));
}

Something like this perhaps:

var re = /^(([0-9]{1,4})(\.[0-9]{1,2})?)$/;
var match = re.exec(subject);
if (match != null) {
    result = match[1];
} else {
    result = "";
}

/^\d{1,digits_before_decimal}$|(?=^.{1,char_count_with_decimal}$)^\d{0,digits_before_decimal}.\d{0,digits_after_decimal}$/;

In your example it is

/^\d{1,4}$|(?=^.{1,7}$)^\d{0,4}.\d{0,2}$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM