+1  A: 

What flavor of regex? In JavaScript, for instance, this'll do it:

var re = /\{.*\}/;

alert("A: " + re.test("This {is} a match"));
alert("B: " + re.test("This {is not a match"));
alert("C: " + re.test("This } is not a match"));

Alerts A: true, B: false, and C: false.

Most other flavors will be similar.

T.J. Crowder
`alert("D: " + re.test("This {should} not be } a match"));`
Svante
@Svante: At the time I answered, the question didn't indicate that (no examples, virtually no detail at all). Heck, I'm still not sure it does. :-)
T.J. Crowder
+1  A: 
/.*\{.*\}.*/

This would ensure that the string contains an opening curly bracket somewhere before a closing curly bracket, occurring anywhere in the string. However, it wouldn't be able to ensure that there's only one opening and closing curly bracket -- to do that, the .* patterns would have to be changed to something more restrictive.

If you want to experiment and test these regexes out, here's a good site.

Kaleb Brasee
This will match "{abc}{" which is probably not what he wants.
fastcodejava
^[a-zA-Z0-9_\-\. ]*(?:\{[a-zA-Z0-9_\-\.]+\})?[a-zA-Z0-9_\-\. ]*$ is what I need,thanks for all your help
Ybbest
A: 

There is exactly one opening brace and exactly one closing brace in the string, and the closing brace follows the opening brace:

^[^\{\}]\{[^\{\}]\}[^\{\}]$

There any number of braces in the string, but they are not nested (there is never another opening brace before the previous one has been closed), and they are always balanced:

^[^\{\}](\{[^\{\}]\})*[^\{\}]$

Nesting cannot be generally solved by regular expressions.

Svante
However, note that most languages don't use strictly "regular" expressions. As an example, the Perl regex `/(\{(?:[^\{\}]++|(?1))*\})/` will match balanced curly braces.
Anon.
+1  A: 

For this problem regex-based solution is way too heavy. If you have the opportunity of NOT using regexes - don't, simpler statement(s) can handle it just fine.


Even much general problem - checking, if the use of (potentially nested) parentheses is correct - is solvable using simple one-pass loop.

I.e. this is correct

{}{{{}{}}}

while this isn't

{{}

Solution in python (easy to translate to other language):

def check(s):
    counter = 0
    for character in s:
        if character == "{":
            counter += 1
        elif character == "}":
            counter -= 1

        if counter < 0:
            # not valid
            return False

    if counter == 0:
        # valid
        return True
    else:
        return False
gorsky
I think that this code snippet contains a syntax error.
Svante
Good point, fixed typo.
gorsky
The lexer will still complain.
Svante
..hope this will work :P (indentation-related issues)
gorsky