简体   繁体   中英

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:

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 .

The \(([^()#]+) regex matches

  • \( - a ( char
  • ([^()#]+) - Capturing group 1 ( match ): any one or more chars other than parentheses and # .

The hyphen is used since the whole-match value is not necessary, we are only interested to get Group 1 value.

Sometimes using regular expressions is error prone and/or overkill.

Here's an alternate answer using split:

lindex [split $string "()#"] 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM