Shortcuts You can use 2 special regex syntax rules to make the pattern more concise:
When a token may or may not be matched, instead of {0,1}
, it can be done with ?
instead - they're exactly equivalent.
When you want to match a digit from 0 to 9, rather than writing out [0-9]
, you can use \d
instead (they're exactly equivalent):
Typo? Regular expressions in JS are delimited by forward slashes, not backslashes.
Prefer const
- Unless you plan on reassigning the regExp
variable name, better to use const
- only use let
when you need to warn readers that the variable may be reassigned.
Missing semicolon Unless you're an expert and can avoid the pitfalls of Automatic Semicolon Insertion, I'd highly recommend using semicolons whenever appropriate, else you will occasionally run into hard-to-understand bugs.
Bug? You probably only want to match digits if they fulfill all the rules - I doubt you want to match the 30
part of 300
, for example. I'd expect that you want a line that ends with 300 to not match at all, right? Fix it by adding a word boundary at the end:
const regExp = /exp[0-2]?\d{1,2}\b/;
Or, if the digits will always come at the end of the line, use $
and the m
flag instead:
const regExp = /exp[0-2]?\d{1,2}$/m;
https://regex101.com/r/udp9BX/7