Reputation: 68078
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...Upvotes: 4
Views: 345
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
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
Reputation: 154968
In that case use:
/^{[A-Z]+}$/.test(str);
The regexp represents any string of the format:
{
}
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
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
Reputation: 222428
Try this regex...
/^[{}A-Z]+$/
/^[{}A-Z]+$/.test("{VARIABLE}") // => true
Upvotes: 1
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