Jump to content

String matching: Difference between revisions

→‎{{header|Tailspin}}: syntax update also adding new possible solution and improving index-counter
(Add min)
(→‎{{header|Tailspin}}: syntax update also adding new possible solution and improving index-counter)
Line 3,684:
 
=={{header|Tailspin}}==
This assumes the string to be found does not contain any regex special characters, otherwise we should work with composers (parsers) see below.
<lang tailspin>
templates find@&{s:}
when <'$s;.*'> do '$; starts with $s;' !
when <'.*$s;'> do '$; ends with $s;' !
when <'.*$s;.*'> do '$; contains $s;' !
<>otherwise '$s; cannot be found in $;' !
end find
'abcd' -> find&{s:'ab'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'cd'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'bc'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find&{s:'e'} -> !OUT::write
</lang>
{{out}}
<pre>
abcd starts with ab
abcd ends with cd
abcd contains bc
e cannot be found in abcd
</pre>
 
Working with composers and literal matchers to be able to handle any string.
<lang tailspin>
composer startsWith&{s:}
@: 0;
(<='$s;'>? -> @:1; <'.*'>) $@
end startsWith
 
composer endsWith&{s:}
@: 0;
(<ends|'.*'>) $@
rule ends: (<~='$s;'>? <='$s;'> -> @:1;)
end endsWith
 
composer contains&{s:}
@: 0;
(<~='$s;'>? <='$s;'>? -> @:1; <'.*'>) $@
end contains
 
templates find&{s:}
when <?($ -> startsWith&{s:$s} <=1>)> do '$; starts with $s;' !
when <?($ -> endsWith&{s:$s} <=1>)> do '$; ends with $s;' !
when <?($ -> contains&{s:$s} <=1>)> do '$; contains $s;' !
otherwise '$s; cannot be found in $;' !
end find
 
'abcd' -> find@&{s:'ab'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find@&{s:'cd'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find@&{s:'bc'} -> !OUT::write
'
' -> !OUT::write
'abcd' -> find@&{s:'e'} -> !OUT::write
</lang>
{{out}}
Line 3,711 ⟶ 3,756:
</pre>
 
In tailspin we don't manipulate strings by character indices but we can still work out the second part. String characters can be streamed and captured in an array, although we prefer to compare in strings, here with a composer (parser).
This has also been crafted to work with strings containing special regex characters by using literal equality.
<lang tailspin>
composer index@&{s:}
@index: 0;
[<match>* -> \(@index: $@index + $; $@index!\)] (<'.*'>)
rule match: (def pos: [<~='$s;'>? ...] -> @: $::length@ + 1; <'(?=+ $s::length;) <'.'>)? -> $pos@
end index
 
'ba is found in positions $:'banana' -> index@&{s:'ba'}; in banana' -> !OUT::write
'
' -> !OUT::write
'ana is found in positions $:'banana' -> index@&{s:'ana'}; in banana' -> !OUT::write
'
' -> !OUT::write
'c is found in positions $:'banana' -> index@&{s:'c'}; in banana' -> !OUT::write
</lang>
{{out}}
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.