Reputation: 939
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
Reputation: 1759
Note that any regex special characters are effectively escaped by putting them inside a range (i.e. square brackets). So:
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
Reputation: 33918
To allow escapes inside your braces you can use:
{((?:[^\\{}]+|\\.)*)}
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
Reputation: 13635
\{(.+)\}
would extract everything between the first and last curly bracket
Upvotes: 0