Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to match a string that starts from 100 to 300

I have several strings like

enter image description here

I need to match the strings that start wih >=100 and <=300 folowed by space and then any string.

The expected result is

enter image description here

I have tried with

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

But this matched incorrectly giving 301, 399 and so on. How do I correct it?

like image 638
Code Guy Avatar asked Dec 07 '25 14:12

Code Guy


1 Answers

If you're absolutely set on a regex solution, try looking for 100 - 299 or 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

You can then use this to filter your strings with a test

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; }
like image 169
Phil Avatar answered Dec 10 '25 05:12

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!