String matching: Difference between revisions
Content added Content deleted
m (curation) |
(→{{header|Tcl}}: Another way to solve this) |
||
Line 161: | Line 161: | ||
set isSuffix [string equal $needle [string range $haystack end-[expr {[string length $needle]-1}] end]]</lang> |
set isSuffix [string equal $needle [string range $haystack end-[expr {[string length $needle]-1}] end]]</lang> |
||
Of course, in the cases where the needle is a glob-safe string (i.e., doesn't have any of the characters “<tt>*?[</tt>” in), this can be written far more conveniently: |
Of course, in the cases where the needle is a glob-safe string (i.e., doesn't have any of the characters “<tt>*?[\</tt>” in), this can be written far more conveniently: |
||
<lang tcl>set isPrefix [string match $needle* $haystack] |
<lang tcl>set isPrefix [string match $needle* $haystack] |
||
set isContained [string match *$needle* $haystack] |
set isContained [string match *$needle* $haystack] |
||
set isSuffix [string match *$needle $haystack]</lang> |
set isSuffix [string match *$needle $haystack]</lang> |
||
Another powerful technique is to use the regular expression engine in literal string mode: |
|||
<lang tcl>set isContained [regexp ***=$needle $haystack]</lang> |
|||
This can be extended by getting the <code>regexp</code> to return the locations of the matches, enabling the other forms of match to be done: |
|||
<lang tcl>set matchLocations [regexp -indices -all -inline ***=$needle $haystack] |
|||
# Each match location is a pair, being the index into the string where the needle started |
|||
# to match and the index where the needle finished matching |
|||
set isContained [expr {[llength $matchLocations] > 0}] |
|||
set isPrefix [expr {[lindex $matchLocations 0 0] == 0}] |
|||
set isSuffix [expr {[lindex $matchLocations end 1] == [string length $haystack]-1}] |
|||
set firstMatchStart [lindex $matchLocations 0 0] |
|||
puts "Found \"$needle\" in \"$haystack\" at $firstMatchStart" |
|||
foreach location $matchLocations { |
|||
puts "needle matched at index [lindex $location 0]" |
|||
}</lang> |