Alex
Alex

Reputation: 68078

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

Oh, very important:

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

Upvotes: 4

Views: 345

Answers (7)

Andrzej Doyle
Andrzej Doyle

Reputation: 103847

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

Upvotes: 6

Joko Wandiro
Joko Wandiro

Reputation: 1987

Jquery Code:

$(document).ready( function(){                          
   $('#test_regex').click( function(){
      regex= /^{[A-Z]+}$/;
      str= $('#reginput').val();
      result= regex.test(str);
      if( result ){
        alert("It's the correct value, yes it's right");
      }else{
        alert("It's incorrect value.. You know");
      }
   });
});

HTML Code:

<input type="text" id="reginput"/>
<button id="test_regex">Check Value</button>

It will return alert("It's the correct value, yes it's right"), if value is {UPPERCASELETTERS}

Upvotes: 1

pimvdb
pimvdb

Reputation: 154968

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).

Upvotes: 6

SaravananArumugam
SaravananArumugam

Reputation: 3720

Use this expression.

[A-Z{}]*

Here the square brackets [] insist on what characters to be present and * says that this patter can repeat multiple times.

Upvotes: 1

Dogbert
Dogbert

Reputation: 222428

Try this regex...

/^[{}A-Z]+$/

/^[{}A-Z]+$/.test("{VARIABLE}") // => true

Upvotes: 1

David Amey
David Amey

Reputation: 1411

Do a negative regex match. If you match something like /[^A-Z{}]/ and get a success, then the string contains something that's "not allowed".

Upvotes: 2

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56222

Use this regex: ^[A-Z{}]+$. It allows only A-Z and {}

Upvotes: 2

Related Questions