问题描述
限时送ChatGPT账号..我有一个字符串 xxxxxxx-s12345ab7_0_0_xx2.log
并且需要在 TCL 中有一个类似 AB700_xx2
的输出.
I have a string xxxxxxx-s12345ab7_0_0_xx2.log
and need to have an output like AB700_xx2
in TCL.
ab
将是分隔符,需要从 ab
提取到 .
(包括 ab
),并且必须只删除前两个下划线.
ab
will be the delimiter and need to extract from ab
to .
(including ab
) and also have to remove only the first two underscores.
试过string trim
、string trimleft
和string trimright
,但用处不大.TCL中有没有类似string split
的东西?
Tried string trim
, string trimleft
and string trimright
, but not much use. Is there anything like string split
in TCL?
推荐答案
第一阶段是提取基本的相关子串;最简单的方法实际上是使用正则表达式:
The first stage is to extract the basic relevant substring; the easiest way to do that is actually with a regular expression:
set inputString "xxxxxxx-s12345ab7_0_0_xx2.log"
if {![regexp {ab[^.]+} $inputString extracted]} {
error "didn't match!"
}
puts "got $extracted"
# ===> got ab7_0_0_xx2
然后,我们想用string map
去掉那些讨厌的下划线:
Then, we want to get rid of those nasty underscores with string map
:
set final [string map {"_" ""} $extracted]
puts "got $final"
# ===> ab700xx2
嗯,不是我们想要的!我们想保留最后一个下划线,并将第一部分大写.
Hmm, not quite what we wanted! We wanted to keep the last underscore and to up-case the first part.
set pieces [split $extracted "_"]
set final [string toupper [join [lrange $pieces 0 2] ""]]_[join [lrange $pieces 3 end] "_"]
puts "got $final"
# ===> got AB700_xx2
(split
命令通过可选的记录说明符(默认为任何空白字符)将字符串分成记录",然后我们可以通过列表操作轻松操作.join
命令执行相反的操作,但在这里我在一半上使用了一个空记录说明符,这使得所有内容都被连接起来.我想你可以猜到 string toupper
和 lrange
命令做...)
(The split
command divides a string up into "records" by an optional record specifier — which defaults to any whitespace character — that we can then manipulate easily with list operations. The join
command does the reverse, but here I'm using an empty record specifier on one half which makes everything be concatenated. I think you can guess what the string toupper
and lrange
commands do…)
这篇关于TCL字符串操作和提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论