【问题标题】:TCL: regexp exclude strings having charactersTCL:正则表达式排除具有字符的字符串
【发布时间】:2012-11-22 11:34:56
【问题描述】:

我不太擅长 TCL 或使用 TCL 正则表达式。但是我需要一个 TCL 机制/正则表达式,如果给定一行/句子,它可以排除或让知道一个单词有一些特殊字符。

假设我有如下一行/句子:

 (space)(space)At 4:00:00AM (not sure) please do your work ...

现在我尝试使用 foreach 拆分行以使每个单词循环:

% set fields [split "   At 4:00:00AM (not sure) please do your work" " " ]
{} {} {} At 4:00:00AM (not sure) please do your work

但我又不想要空字段:

% foreach val $fields {
       puts $val
}



At
4:00:00AM
(not
sure)
please
do
your
work

除此之外,我想排除 foreach 循环中具有特殊字符的单词,例如:

(not
sure)
4:00:00AM

排除在 start 、 end 或单词中任何位置包含 '(' 或 ':' 的单词。

请告诉我如何才能做到这一点。

【问题讨论】:

    标签: tcl


    【解决方案1】:
    set str "   At 4:00:00AM (not sure) please do your work"
    
    # split the string into space-delimited words
    set words [regexp -inline -all {\S+} $str]
    
    # eliminate words containing a character other than letters, numbers, underscore
    set alnum_words [lsearch -inline -regexp -all -not $words {\W}]
    

    alnum_words 现在包含列表{At please do your work}

    如果您只想要仅由字母组成的单词,请使用

    lsearch -inline -regexp -all $words {^[[:alpha:]]+$}
    

    【讨论】:

      【解决方案2】:

      不幸的是,Tcl 正则表达式不支持后视运算符。否则,可以使用单个正则表达式来实现。 但是,您可以使用以下代码来构建您需要的单词列表:

      set the_line "   At 4:00:00AM (not sure) please do your work"
      set fields {}
      foreach {- val} [regexp -all -inline -- {(?:^|\s)([^:()\s]+(?=\s|$))} $the_line] {
          lappend fields $val
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-17
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 2021-09-16
        • 2017-04-13
        • 1970-01-01
        相关资源
        最近更新 更多