Version 1 of Search pattern list

Updated 2015-10-08 12:02:23 by he

HE 2015-10-08: lsearch returns the first element in list that matches pattern, or -1 if there are no matches.

I want to have the first pattern in list that matches value, or -1 if there are no matches.

Here is my solution:

Syntax: searchPatList mode value patList

where mode is one of:

  • -exact = The index of the first pattern from patList which match exactly value will be returned. Or -1 in case of no match.
  • -glob = The index of the first pattern (glob style) from patList which match value will be returned. Or --1 in case of no match.
  • -regexpt = The index of the first pattern (regulaer Expression) from patList which match value will be returned. Or --1 in case of no match

and value is a string to check if one of the pattern matches.

and patList is a list of pattern. The kind of pattern is defined by mode.

proc searchPatList {mode value patList} {
        set n 0
        switch -exact -- $mode {
                -exact {
                        foreach el $patList {
                                if {$el eq $value} {
                                        return $n
                                }
                                incr n
                        }
                        return -1
                }
                -glob {
                        foreach el $patList {
                                if {[string match $el $value]} {
                                        return $n
                                }
                                incr n
                        }
                        return -1
                }
                -regexp {
                        foreach el $patList {
                                if {[regexp -- $el $value]} {
                                        return $n
                                }
                                incr n
                        }
                        return -1
                }
                default {
                        error "Unknown mode '$mode'!"
                }
        }
        return
}

And the examples:

set patList [list \
        {test 3.4.1} \
        {dummy} \
        {^test *[0-9.]*$} \
        {test *} \
]

searchPatList -exact {test 3.4.1} $patList
0
searchPatList -exact {test 3.4.2} $patList
-1
searchPatList -exact {dummy} $patList
1
searchPatList -glob {test 3.4.1} $patList
0
searchPatList -glob {test 3.4.2} $patList
3
searchPatList -glob {dummy} $patList
1
searchPatList -regexp {test 3.4.1} $patList
0
searchPatList -regexp {test 3.4.2} $patList
2
searchPatList -regexp {dummy} $patList
1
searchPatList -default {dummy} $patList
Unknown mode '-default'!