簡體   English   中英

正則表達式匹配從 100 到 300 的字符串

[英]regex to match a string that starts from 100 to 300

我有幾個字符串

在此處輸入圖像描述

我需要匹配以 >=100 和 <=300 開頭的字符串,然后是空格,然后是任何字符串。

預期的結果是

在此處輸入圖像描述

我試過了

[123][0-9][0-9]\s.*

但這匹配錯誤地給出 301、399 等等。 我該如何糾正?

如果您完全使用正則表達式解決方案,請嘗試尋找 100 - 299300

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 如果您更改模式以匹配1xx2xx300 ,那么它將按照您的預期返回結果,即:

/^([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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM