Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if a string is made up with a certain set of characters

How can I out if a string only contains a certain set of characters: { A-Z and } ?

For example

  • {VARIABLE} => should return true
  • {VARiABLE} => should be false, because there's a lowercase i inside
  • { VARIABLE} => should be false because there's a space etc.

Oh, very important:

the string MUST have at least one character between { and }, so:

  • {} should be false too...
like image 576
Alex Avatar asked Dec 01 '22 02:12

Alex


2 Answers

In that case use:

/^{[A-Z]+}$/.test(str);

The regexp represents any string of the format:

  • First a {
  • Then one or more capital letters
  • Then a }

The ^...$ makes sure that the string should be exactly of this form, rather than a substring only (otherwise test{AAA} would match too).

like image 68
pimvdb Avatar answered Dec 03 '22 15:12

pimvdb


This sounds like a good case to use regular expressions. In particular, regexes allow one to match a range of characters - [A-Z{}] would match any character which is either an uppercase letter, {, or }.

EDIT based on new requirements - you want to match something that starts with a literal {, then has at least one character in the range A-Z, then a closing }. Which gives the regex:

{[A-Z]+}

Thus you could match against the entire regex:

val input = "{VARIABLE}"
return input.test(/{[A-Z]+}/) // returns true

"{VARiABLE}".test(/{[A-Z]+}/) // returns false
"{ VARIABLE}".test(/{[A-Z]+}/) // returns false

"".test(/{[A-Z]+}/) // returns false - open bracket didn't match
"{}".test(/{[A-Z]+}/) // returns false - A-Z part didn't match
like image 37
Andrzej Doyle Avatar answered Dec 03 '22 15:12

Andrzej Doyle