Amit
Amit

Reputation: 939

Regex to find string without curly braces but "\{", "\}" is allowed

I have a regex to find string without curly braces "([^\{\}]+)". So that it can extract "cde" from follwing string:

"ab{cde}f"

Now I need to escape "{" with "\{" and "}" with "\}".

So if my original string is "ab{cd\{e\}}f" then I need to extract "cd{e}" or "cd\{e\}" (I can remove "\" later).

Thanks in advance.

Upvotes: 1

Views: 4746

Answers (4)

Graham
Graham

Reputation: 1759

Note that any regex special characters are effectively escaped by putting them inside a range (i.e. square brackets). So:

  • [.] matches a literal period.
  • [[] matches a left square bracket.
  • [a] matches the letter a.
  • [{] matches a left curly brace.

So:

$ echo "ab{cde}f" | sed -r 's/[^{]*[{](.+)}.*/\1/'
cde
$ echo "ab{c\{d\}e}f" | sed -r 's/[^{]*[{](.+)}.*/\1/'
c\{d\}e

Or:

$ echo "ab{cde}f" | sed 's/[^{]*{//;s/}[^}]*$//'
cde
$ echo "ab{c\{d\}e}f" | sed 's/[^{]*{//;s/}[^}]*$//'
c\{d\}e

Or even:

$ php -r '$s="ab{cde}f"; print preg_replace("/[^{]*[{](.+)}.*", "$1", $s) . "\n";'
cde
$ php -r '$s="ab{c\{d\}e}f"; print preg_replace("/[^{]*[{](.+)}.*/", "$1", $s) . "\n";'
c\{d\}e

Obviously, this does not handle escaped backslashes. :-)

Upvotes: 2

user1096188
user1096188

Reputation: 1839

This should work:

([^{}\\]|\\{|\\})+

Upvotes: 2

Qtax
Qtax

Reputation: 33918

To allow escapes inside your braces you can use:

{((?:[^\\{}]+|\\.)*)}

Perl example:

my $str = "ab{cd\\{e\\}} also foo{ad\\}ok\\{a\\{d}";
print "$str\n";
print join ', ', $str =~ /{((?:[^\\{}]+|\\.)*)}/g;

Output:

ab{cd\{e\}} also foo{ad\}ok\{a\{d}
cd\{e\}, ad\}ok\{a\{d

Upvotes: 2

Ben
Ben

Reputation: 13635

\{(.+)\} would extract everything between the first and last curly bracket

Upvotes: 0

Related Questions