正则表达式匹配从100到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; }


回答

那是因为在您的模式中,它还匹配3xxwherex可以是任何数字,而不仅仅是0. 如果你改变你的模式匹配1xx2xx300随后在按预期它会返回结果,即:

/^([12][0-9][0-9]|300)s.*/g
/^([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);


以上是正则表达式匹配从100到300的字符串的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>