Forum Discussion
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 [email protected]" into 2 variables - $garbage = "USER username" and $siteman = "sitename.com"
This works fine until the username proportion contains a "@".
So "USER username@[email protected]" now splits into 2 variables $garbage = "USER username" and $sitename = "[email protected]".
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
and[string last]
to find the position of the last occurrence and to cut the leading/trailing values.[string range]set input "test@[email protected]" 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]
and[lindex]
to create and select the required[join]
entries and to format the resulting string.[list]set input "test@[email protected]" 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
Recent Discussions
Related Content
* Getting Started on DevCentral
* Community Guidelines
* Community Terms of Use / EULA
* Community Ranking Explained
* Community Resources
* Contact the DevCentral Team
* Update MFA on account.f5.com