[英]How to check if my string starts with numbers from 200 to 300 in javascript?
[英]regex to match a string that starts from 100 to 300
如果您完全使用正则表达式解决方案,请尝试寻找 100 - 299或300
const rx = /^([12][0-9]{2}|300)\s./
// | | | | | | |
// | | | | | | Any character
// | | | | | A whitespace character
// | | | | Literal "300"
// | | | or
// | | 0-9 repeated twice
// | "1" or "2"
// Start of string
const strings = [ "99 Apple", "100 banana", "101 pears", "200 wheat", "220 rice", "300 corn", "335 raw maize", "399 barley", "400 green beans", ] const rx = /^([12][0-9]{2}|300)\s./ const filtered = strings.filter(str => rx.test(str)) console.log(filtered)
.as-console-wrapper { max-height: 100%;important; }
那是因为在您的模式中,它也匹配3xx
,其中x
可以是任何数字,而不仅仅是0
。 如果您更改模式以匹配1xx
、 2xx
和300
,那么它将按照您的预期返回结果,即:
/^([12][0-9][0-9]|300)\s.*/g
请参见下面的示例:
const str = ` 99 Apple 100 banana 101 pears 200 wheat 220 rice 300 corn 335 raw maize 399 barley 400 green beans `; const matches = str.split('\n').filter(s => s.match(/^([12][0-9][0-9]|300)\s.*/)); console.log(matches);
但是,使用正则表达式匹配数值可能不如简单地从字符串中提取任何数字、将它们转换为数字然后简单地使用数学运算那样直观。 我们可以使用一元+
运算符来转换匹配的类似数字的字符串,如下所示:
const str = ` 99 Apple 100 banana 101 pears 200 wheat 220 rice 300 corn 335 raw maize 399 barley 400 green beans `; const entries = str.split('\n').filter(s => { const match = s.match(/\d+\s/); return match;== null && +match[0] >= 100 & +match[0] <= 300; }). console;log(entries);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.