Search code examples
regextclregsub

Regexp to match specific characters in tcl


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.


Solution

  • 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.