regexp fails to match braces inside a character class
Closed / Invalid05beaa6eef4fdb97d6fb518f0508c108c010c548Created 13 years agoUpdated 13 years ago
Descriptionhtml2014-02-15 01:54:00
I want to match a set of characters including letters, spaces, brackets and braces between two words:
% set ptn {the ([\w\{\}\[\]\s]+) test}
the ([\w\{\}\[\]\s]+) test
# Words and spaces match
% regexp -inline $ptn {the abc def test}
{the abc def test} {abc def}
# Words and square brackets match
% regexp -inline $ptn {the abc][def test}
{the abc][def test} {abc][def}
# Even a single square bracket will match
% regexp -inline $ptn {the [ test}
{the [ test} {[}
# But tcl fails to match braces:
% regexp -inline $ptn {the abc\}\{def test}
% regexp -inline $ptn {the abc\{def test}
% regexp -inline $ptn {the \{ test}
ericp (claiming to be Ref Komodo bug)plain2014-02-15 01:55:38
http://bugs.activestate.com/show_bug.cgi?id=102789
ericpplain2014-02-15 02:15:56
I figured out that I have to triple-escape the braces in the character class.
dkfhtml2014-02-15 15:08:43
I'm confused by what you thought you were matching. In particular, I suspect that the string you were matching against was not what you thought it was. Also, it's really best to put the close square bracket at the start of a match set, and you don't need nearly so many backslashes.
% set ptn {the ([][{}\w\s]+) test}
the ([][{}\w\s]+) test
% regexp -inline $ptn {the abc def test}
{the abc def test} {abc def}
% regexp -inline $ptn {the abc][def test}
{the abc][def test} {abc][def}
% regexp -inline $ptn {the [ test}
{the [ test} {[}
What were you meaning to have as the strings you matched against?
% regexp -inline $ptn {the abc\}\{def test}
% regexp -inline $ptn "the abc\}\{def test"
the\ abc\}\{def\ test abc\}\{def
% # That looks confusing; once more, with list extraction!
% foreach bit [regexp -inline $ptn "the abc\}\{def test"] {puts [incr i]=>$bit}
1=>the abc}{def test
2=>abc}{def
% puts {the abc\}\{def test}
the abc\}\{def test
% puts "the abc\}\{def test"
the abc}{def test
That is, were you intending to have a literal backslash in the match set? In case you were, here's a working, minimal version. (Braces aren't special to RE character sets per se but they can interact with how you're quoting the string.)
% ### NOTE THE EXTRA PAIR OF BACKSLASHES; ONLY DIFFERENCE! ###
% set ptn {the ([][{}\w\s\\]+) test}
the ([][{}\w\s\\]+) test
% regexp -inline $ptn {the abc\}\{def test}
{the abc\}\{def test} {abc\}\{def}
Some general comments. Embedded unbalanced braces break brace-quoting of literals. Always have (since one of the very earliest versions). This isn't much of an issue normally as they're pretty rare except in test data. The list-quoting engine copes by switching to a different quoting style, as you might guess from the output traces above.
Log in (anonymous is fine) to add a comment.