![](/img/trans.png)
[英]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.