Forum Discussion

RoutingLoop_179's avatar
Mar 28, 2017

Scan or split to find last instance of character.

Hi is there an efficient way to find the last occurrence of a character in a string and split into 2 variables.

 

Currently I use "scan [TCP::payload] {%[^@]@%s} garbage sitename"

 

This splits "USER username@sitename.com" into 2 variables - $garbage = "USER username" and $siteman = "sitename.com"

 

This works fine until the username proportion contains a "@".

 

So "USER username@something@sitename.com" now splits into 2 variables $garbage = "USER username" and $sitename = "something@sitename.com".

 

What I'm trying to achieve is an efficient way of getting $garbage = "USER username@something" and $sitename = "sitename.com". I've looked at TCL split and index but I'll end up with multiple variables which I have to join back up and it won't be consistent as username proportion won't always contain an @, so sometimes i'll have 2 variables others three or (maybe even more if user has used multiple @ in their username).

 

If anyone has any pointers that'd be great.

 

1 Reply

  • Hi RoutingLoop,

    you may try a combination of

    [string last]
    and
    [string range]
    to find the position of the last occurrence and to cut the leading/trailing values.

    set input        "test@test@test.de"
    set last_at       [string last "@" $input]
    set leading_part  [string range $input 0 [expr { $last_at - 1 }]]
    set trailing_part [string range $input [expr { $last_at + 1 }] end]
    

    ... or you could try a combination of

    [split]
    ,
    [lrange]
    ,
    [lindex]
    and
    [join]
    to create and select the required
    [list]
    entries and to format the resulting string.

    set input         "test@test@test.de"
    set input_list    [split $input "@" ]
    set leading_part  [join [lrange $input_list 0 end-1] "@"]
    set trailing_part [lindex $input_list end]
    

    Note: Performance wise both example are almost equal. So it will depend only on your personal preferences.

    Cheers, Kai