0

我想检查该行是否为键值格式,所以我这样做:

        set index [string first "=" $line]

        if { $index == -1 } {
            #error
        }

        set text  [string range $line [expr $index + 1] end]

        if { [string first "=" $text ] != -1 } {
            #error
        }

如何将此检查写为正则表达式?

4

2 回答 2

4

您还可以使用分隔符拆分字符串=并检查结果字段的数量

set fields [split $line =]
switch [llength $fields] {
    1 {error "no = sign"}
    2 {lassign $fields key value}
    default {error "too many = signs"}
}
于 2013-05-29T11:51:30.860 回答
2

if对于最后一条语句,您的代码有点令人困惑。

通过正则表达式,您可以使用:

% regexp {=(.*)$} $line - text
1 # If there's no "=", it will be zero and nothing will be stored in $text, 
  # as $text will not exist

在一个if块中,您可以使用:

if {[regexp {=(.*)$} $line - text]} {
    puts $text
} else {
    # error
}

编辑:检查字符串是否只包含一个=符号:

if {[regexp {^[^=]*=[^=]*$} $line]} {
    return 1
} else {
    return 0
}

^表示字符串的开头。
[^=]表示除等号以外的任何字符。
[^=]*表示除等号以外的任何字符出现 0 次或多次。
=只匹配一个等号。
$匹配字符串的结尾。

因此,它检查字符串是否只有一个等号。

1表示该行仅包含 1 个等号,0表示没有等号,或多于 1 个等号。

于 2013-05-29T10:53:57.857 回答