Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to ignore special characters

1,024 views
Skip to first unread message

balajee

unread,
Oct 7, 2011, 4:57:17 AM10/7/11
to
Hi,
Is there a way to ignore special characters while doing regexp. For
Eg, I am getting the following error while doing regexp in one of my
scripts.

% regexp $a $b
couldn't compile regular expression pattern: parentheses () not
balanced

This is expected because I have unbalanced braces in my variables.
But, I can not modify the variables due to other reasons. I want to
ignore all special characters like ),(,- etc. Please let me know if
anybody has any idea.

Thanks,
Balajee

Uwe Klein

unread,
Oct 7, 2011, 6:03:43 AM10/7/11
to
run your $a through a proc that escapes all specials?

proc re_escape expr {
set expr [ split $expr {} ]
foreach char $expr {
switch -- $char \
( - ) {
lappend res \\ $char
} \{ - \} {
lappend res \\ $char
} \[ - \] {
lappend res \\ $char
} .... - ... {
# more?
} default {
lappend res $char
}
}
return [join $res {}]
}

uwe

arjenmarkus

unread,
Oct 7, 2011, 6:16:35 AM10/7/11
to
Hello,

characters are escaped via \. For instance:

regexp {\(.*} $someString

to find the (longest) substring starting with a open parenthesis.

To escape all (, ), ...:

regexp [string map {( \\( ) ) \\) ...} $a] $b

The [string map] command is powerful but be aware: it substitutes all
patterns without regard for context.

Regards,

Arjen

Bruce

unread,
Oct 7, 2011, 10:07:19 AM10/7/11
to
If you want to ignore *all* special characters, the you could just
switch to using [string first ...]

if you really want to use regexp, but want to match literal strings
you could follow the opthers advice to pre-process and escape all
special characters or use one of the following:

regexp "***=$a" $b

or

regexp "(?q)$a" $b


If you wnt to allow *some* special characters but not others, then
you will need to do the escaping yourself.

Bruce

Wouter Snels

unread,
Oct 9, 2011, 6:12:42 AM10/9/11
to
Op 07-10-11 10:57, balajee schreef:
% set list
a bc \{ \ ] )
% split $list
a bc {\{} \\ \] )
% set list
a bc \{ \ ] )
% string map {\{ \\{ \} \\} \\ \\\\ \[ \\[ \] \\] \( \\( \) \\) \" \\"
\' \\'} $list
a bc \\\{ \\ \] \)
%

Regards, ..
0 new messages