正则表达式匹配从 100 到 300 的字符串

Cod*_*Guy 3 javascript regex

我有几个像

在此处输入图片说明

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

预期的结果是

在此处输入图片说明

我试过

[123][0-9][0-9]\s.*
Run Code Online (Sandbox Code Playgroud)

但是这个匹配错误地给出了 301、399 等等。我该如何纠正?

Phi*_*hil 6

如果您绝对使用正则表达式解决方案,请尝试查找 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
Run Code Online (Sandbox Code Playgroud)

然后您可以使用它通过测试过滤您的字符串

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)
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; }
Run Code Online (Sandbox Code Playgroud)


Ter*_*rry 5

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

/^([12][0-9][0-9]|300)\s.*/g
Run Code Online (Sandbox Code Playgroud)

请参阅下面的示例:

/^([12][0-9][0-9]|300)\s.*/g
Run Code Online (Sandbox Code Playgroud)

但是,使用正则表达式匹配数值可能不如简单地从字符串中提取任何数字,将它们转换为数字,然后简单地使用数学运算直观。我们可以使用一元运算+符来转换匹配的类似数字的字符串:

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);
Run Code Online (Sandbox Code Playgroud)