TCL字符串操作和提取

编程入门 行业动态 更新时间:2024-10-27 22:25:18
本文介绍了TCL字符串操作和提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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 trimstring trimleftstring 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 toupperlrange 命令做...)

(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:关键词]

本文发布于:2023-05-01 09:18:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1407280.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   操作   TCL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!