0

I have two type of input,

str_1 = 'rb_done_1' 
str_2 = 'rb_${4}done'

I need regex to match true only one. My best try is :

reg_1 = '(^[a-zA-z0-9_]+[^{}$]$)' # returns true for 1 and false for 2, this is desired output
reg_2 = '(^[a-zA-z0-9_][\${}]+$)' # returns false for both case, should return false for 1 and true for 2

^ .. $ is used to make a full string match. in reg_2 I am trying to match one or more character from 'a-zA-z0-9_' and one or more from '${}' ( must have at least one to differentiate two type of input).

1 Answers1

0

About the patterns you tried

  • The first pattern ^[a-zA-z0-9_]+[^{}$]$ matches the first string because the last part [^{}$] is a negated character class which will match any char except what is listed in the character class.

    That means that the 1 at the end of rb_done_1 will be matched by [^{}$]

  • The second pattern ^[a-zA-z0-9_][\${}]+$ does not match both, because the character class at the start does not have a quantifier but the second one has, meaning that the second character of the string until the end has to be one of $ { or }

Note that A-z is not the same as A-Za-z


For the first string you could match 1+ times a word character.

^\w+$

Regex demo


For the second string you could use a positive lookahead (?= to make sure there is at least a single char $ { or } and make sure that there is at least a single word character

^(?=.*[${}])(?=.*\w)[\w${}]+$

Regex demo

Or use negated character classes which is more efficient but a slightly longer pattern

^(?=[^${}\r\n]*[${}])(?=[^\w\r\n]*\w)[\w${}]+$

Regex demo

Community
  • 1
  • 1
The fourth bird
  • 154,723
  • 16
  • 55
  • 70