java正整数正则表达式_如何使用正则表达式检查字符串是否是一个不以0开头的正整数?…

  • Post author:
  • Post category:java


经过大量研究后,我还没有发现满足所有这些IF条件的正则表达式 . 代码效果很好,但我认为可以使用RegEx简化 .

目标:在1到9之间的正整数上返回true,而不是从零开始 . 为每个其他值返回false .

看一看 .

// Validation functions

function hasPeriod(s) {

// Return true or false.

// True if a period is entered at any point in time.

return s.indexOf(‘.’) > -1;

}

// See more… http://2ality.com/2014/05/is-integer.html

function isInteger(s) {

// Return true or false.

// True if the remainder of dividing it by 1 is 0.

return s % 1 === 0;

}

// Bind keyup event to prep_work_item_input.

$(‘#input1’).on(‘keyup’, function (e) {

// TRIM text input value on declaration…

// May contain spaces…

var input_value = $(this).val().trim();

// Refresh text input after Trim!

// Does not contain spaces

$(this).val(input_value);

// If text input is EMPTY after Trim…

if (input_value.length == 0) {

// Stop at this if and dont proceed.

return false;

}

// If a PERIOD is typed into text input at any point in time…

if (hasPeriod(input_value)) {

// Clear input

$(this).val(”);

// Stop at this if and dont proceed.

return false;

}

// If text input value is NOT an INTEGER…

if (!isInteger(input_value)) {

// Clear input

$(this).val(”);

// Stop at this if and dont proceed.

return false;

}

// If text input value IS an INTEGER but EQUAL to 0…

if (input_value == 0) {

// Clear input

$(this).val(”);

// Stop at this if and dont proceed.

return false;

}

// If text input value IS an INTEGER and also GREATER than 0…

if (input_value > 0) {

// If we have made this far…

// we probably have a real integer that is not zero.

// We can finally begin to calculate

input_value = parseInt(input_value);

// random cost multiplier for this example

var cost = parseFloat(‘0.78’);

// calculate subtotal…

cost = input_value * cost;

// Set prep_work_item_subtotal…

console.log(input_value + ‘ ‘ + ‘SF’ + ‘ / ‘ + ‘ $’ + cost.toFixed(2));

}

});

Enter value below:



版权声明:本文为weixin_42503076原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。