lsearch
Searches a list for elements matching a pattern and returns their indices or values.
Syntax
tcl
lsearch ?options? list patternParameters
- list: The list to search
- pattern: The pattern to match against
Options
Match type
- -exact: Exact string match (default)
- -glob: Glob-style pattern matching
- -regexp: Regular expression matching
Data type
- -ascii: Compare as strings (default)
- -dictionary: Dictionary-style comparison (handles embedded numbers naturally, e.g., "a2" < "a10")
- -integer: Compare as integers
- -real: Compare as floating-point numbers
Sort order (for -sorted)
- -sorted: List is sorted, use binary search
- -increasing: Ascending order (default with -sorted)
- -decreasing: Descending order
- -bisect: Return index of last element less than or equal to pattern (for sorted lists)
Result control
- -all: Return all matching indices
- -inline: Return matching values instead of indices
- -not: Return elements that do NOT match the pattern
- -start index: Start searching at index (supports
end,end-N, and arithmetic expressions like0+1)
Element selection
- -index indexList: Compare against a specific element within each list item. Can be a single index or a nested index list (e.g.,
-index {0 1}for deep access) - -subindices: Return full index path to matched element (requires
-index) - -stride count: Treat list as groups of count elements, searching only the first element of each group
Modifiers
- -nocase: Case-insensitive matching
Examples
Find first occurrence
Output
Find all occurrences
Output
Get matching values with -inline
Output
Case-insensitive search
Output
Search sorted list
Output
Start from index
Output
Not found returns -1
Output
Find non-matching elements with -not
Output
Search by element index with -index
Output
Search strided lists with -stride
Output
Find insertion point with -bisect
Output
Dictionary-style comparison
Output
Using end-N index expressions
Output
See Also
- lindex - Get element by index
- lsort - Sort list
- string match - String pattern matching
