Reputation: 2908
How to remove brackets from string in Prolog. I have only {} brackets, and there might be nested brackets.
for example if I have a string
a{1+{2}+3}b{4}c
then the answer will be string
abc
Upvotes: 0
Views: 892
Reputation: 40768
This is very easy with dcg notation.
The following assumes that you have the setting:
:- set_prolog_flag(double_quotes, chars).
in your initialization file, to work more conveniently with characters.
For example:
no_braces([]) --> []. no_braces([C|Cs]) --> [C], { dif(C, '{') }, no_braces(Cs). no_braces(Cs) --> ['{'], no_braces(_), ['}'], no_braces(Cs).
Sample queries and answers:
?- phrase(no_braces(Ls), "abc"). Ls = [a, b, c] ; false. ?- phrase(no_braces(Ls), "a{b}c"). Ls = [a, c] ; false.
We can also post very general queries and still obtain answers:
?- length(Ls0, _), phrase(no_braces(Ls), Ls0). Ls0 = Ls, Ls = [] ; Ls0 = Ls, Ls = [_2308], dif(_2308, '{') ; Ls0 = Ls, Ls = [_2474, _2480], dif(_2474, '{'), dif(_2480, '{') ; Ls0 = ['{', '}'], Ls = [] ; Ls0 = Ls, Ls = [_2640, _2646, _2652], dif(_2640, '{'), dif(_2646, '{'), dif(_2652, '{') .
At last, your example:
?- phrase(no_braces(Ls), "a{1+{2}+3}b{4}c"). Ls = [a, b, c] ; false.
Upvotes: 2