Regexp to match specific characters in tcl

2.8k Views Asked by At

I have a variable that contains following characters

"@/$%&*#{}4g_.[]3435_.technology@lte042"

I want to match only "4g_.3435_.technologylte042" by excluding special characters

Code:

set a "@\/$%&*#[](){}4g_.[]3435_.technology@lte042"
regexp {[\w._-]+} $a match
puts $match

I got output :

4g_.3435_.technology

I am not getting remaining characters "lte042"

please help.

2

There are 2 best solutions below

10
On BEST ANSWER

I suppose you are trying to remove all non-word characters, rather than trying to find the first contiguous sequence of word characters. You could use a repeated search-and-replace:

regsub -all {[^\w._-]+} $a "" match

Another option is to use the -all -inline options to produce a list of matches instead of a single match. However, that will put spaces between the successive matches. Eg:

set a "@\/$%&*#[](){}4g_.[]3435_.technology@lte042"
set match [regexp -all -inline {[\w._-]+} $a]
puts $match

==>

4g_.3435_.technology lte042

The second set is necessary because the -inline option doesn't allow match variables to be specified as command parameters.

0
On

One step closer:

% set s {@/$%&*#{}4g_.[]3435_.technology@lte042}
@/$%&*#{}4g_.[]3435_.technology@lte042
% join [regexp -inline -all {[][\w._-]+} $s] {}
4g_.[]3435_.technologylte042

Documentation: join, regexp, set, Syntax of Tcl regular expressions