简体   繁体   English

检查字符串的数字是否大于 1

[英]Check if a string has number greater than 1

I have a method returning me a string that may contain numbers.我有一个方法返回一个可能包含数字的字符串。 I extract those numbers into a string with comma-separated value.我将这些数字提取到一个带有逗号分隔值的字符串中。

var stringOne = "Returned 12 string";
var extractNum = "1,2"

What I want now is to check this string against a regular expression that tests to see if the string has numbers greater than 1?我现在想要的是根据正则表达式检查这个字符串,该表达式测试字符串是否有大于 1 的数字? I've tried few things but none seems to be working.我尝试了几件事,但似乎都没有奏效。 Please suggest a way to accomplish it.请建议一种方法来实现它。 Thanks in advance!提前致谢!

If you just want to test if your extract String containt numbers greater than 1, you can try below code如果您只想测试您的提取字符串是否包含大于 1 的数字,您可以尝试以下代码

function check() {
        var str = "1,1,1,1,2,1,1";
        var patt = new RegExp("[2-9]");
        return patt.test(str); // true
    }

 var matched = "Returned 12 string".match(/[2-9]/g) if (matched !== null) { alert(matched.join(',')); } else { // No match }

You could do the following:您可以执行以下操作:

var extractNum = "1,2";
var hasGreaterThan1 = extractNum.split(',').some(function(val) { return val > 1; })

See documentation for Array.prototype.some请参阅Array.prototype.some文档

Ideally you would parse the number and use the actual numerical operators provided by Javascript to do this.理想情况下,您将解析数字并使用 Javascript 提供的实际数字运算符来执行此操作。

If you really must do it through a regular expression, you could use something like so: ^[2-9]|\\d{2,}$ .如果你真的必须通过正则表达式来做,你可以使用这样的东西: ^[2-9]|\\d{2,}$ This will check that the number is either a single digit between 2 and 9 or else a digit made up from two or more numbers.这将检查数字是 2 到 9 之间的单个数字还是由两个或多个数字组成的数字。

"ok" will be true if any number is bigger than 1;如果任何数字大于 1,则“ok”为真;

var stringOne = "Returned 12 string";
var extractNum = "1,2"
var ok = haveNrBiggerThan1(extractNum);

function haveNrBiggerThan1(str){
    var nums = str.split(",");
    for(var i=0; i<nums.length; i++){var n=parseInt(nums[i]); if(n>1){return true;}}
    return false;
}

不使用正则表达式

extractNum.split(',').map(function(a){return parseInt(a)>1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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