[英]tcl how to split a string by using regexp
I have some string with format我有一些带格式的字符串
class(amber#good)
class(Back1#notgood)
class(back#good)
and I want to use regexp to get value of these string我想使用正则表达式来获取这些字符串的值
Expected answer:预期答案:
amber
Back1
back
And here's my cmd:这是我的 cmd:
set string "class(amber#good)"
regexp -all {^\\([a-zA-z_0-9].\#$} $string $match
puts $match
But the answer is not what I expected但是答案不是我所期望的
You can use您可以使用
regexp {\(([^()#]+)} $string - match
See the Tcl demo online .在线查看 Tcl 演示。
The \(([^()#]+)
regex matches \(([^()#]+)
正则表达式匹配
\(
- a (
char \(
- 一个(
字符([^()#]+)
- Capturing group 1 ( match
): any one or more chars other than parentheses and #
. ([^()#]+)
- 捕获组 1 ( match
):除括号和#
之外的任何一个或多个字符。 The hyphen is used since the whole-match value is not necessary, we are only interested to get Group 1 value.使用连字符是因为不需要整体匹配值,我们只对获取第 1 组值感兴趣。
Sometimes using regular expressions is error prone and/or overkill.有时使用正则表达式容易出错和/或矫枉过正。
Here's an alternate answer using split:这是使用拆分的替代答案:
lindex [split $string "()#"] 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.