Exclusive regex | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Exclusive regex

I found something that doesn't work, but I'd like to discover if it something like that: [a-z-[m]] so should be any low word but not "m" (I know [a-ln-z] bring same result, but isn't I'm looking for). Or [\w&&[\d]] so need be \w AND \d. Challenge: I wanna take one number that can be from 1 up to 20, can be 01 too.. [012]?\d But 119 can be match, so can't have number before nor after. \D([012]?\d\)D: have better?

18th Oct 2020, 9:53 AM
Marcelo Anjos
Marcelo Anjos - avatar
3 Answers
+ 3
To answer your second question first: [\w&&\d] is redundant because \w includes \d anyway so \d here would be enough. Your number problem, you need to match a number 0 or 1 (which may or may not be there) before matching another digit, or match 20. This should do that: ([01]?\d|20) To explain, [01] will match a 0 or a 1, ? means that it doesn't necessarily have to be there, then \d, as you know means any number. () means that the whole expression is inside a "capture group", and | means "or" so that if either expression inside the group matches, the whole group will match. Then 20 matches what you would expect. I just realised you want to exclude numbers before and after, so you'd need [^\d] either side for this. [^\d]([01]?\d|20)[^\d] Why don't you want to use [a-ln-z]?
18th Oct 2020, 11:07 AM
Russ
Russ - avatar
0
To be honest I don't remember when I got this need. But there a moment that I found stuck cause I really want match or exclude things. Like lookahead (:?abc). And sometimes regex would short adding all and exclude two things than add almost all ranges.
18th Oct 2020, 12:35 PM
Marcelo Anjos
Marcelo Anjos - avatar
0
Am not sure i have understood your question but here's a solution Soln: takes 1 to 20 regardless of whether there's a 0 before or not. ^(0?[1-9]|0?1\d{1}|020|20)$
18th Oct 2020, 9:27 PM
Devotha Mwenda
Devotha Mwenda - avatar