1. search
Searches for the first occurrence of a substring within a string.
1.2. Stack Effects
| Level | Object |
|---|---|
1 |
|
0 |
|
| Level | Object |
|---|---|
3 |
|
2 |
|
1 |
|
0 |
|
| Level | Object |
|---|---|
1 |
|
0 |
|
1.3. Description
search looks for the first occurrence of seek within string.
If found, it splits string into three segments: * pre: portion before the match * match: portion matching seek * post: remainder after the match
All three substrings share intervals of the original string value.
If not found, it returns the original string and false.
1.5. Examples
(abbc) (ab) search
% Result: (bc) (ab) () true
% pre is empty because match at start
(abbc) (bb) search
% Result: (c) (bb) (a) true
(abbc) (bc) search
% Result: () (bc) (ab) true
% post is empty because match at end
(abbc) (B) search
% Result: (abbc) false
1.6. Common Use Cases
1.6.1. String Parsing
line (:) search {
exch pop exch pop % Keep only post
} {
pop % No delimiter found
} ifelse
1.7. Common Pitfalls
| Case Sensitive - The search is exact, including case. |
(Hello) (hello) search % false - case mismatch
| Finds Only First Match - Stops at the first occurrence, not all occurrences. |
(abcabc) (ab) search % Finds first 'ab' only
| Stack Order - Results are post, match, pre (reversed from read order). |
(hello) (ll) search % true pre match post
% Actually: true (he) (ll) (o)
Use anchorsearch for Prefixes - If you only need to check the start of a string, anchorsearch is simpler.
|
1.8. Error Conditions
| Error | Condition |
|---|---|
[ |
String has no-access attribute |
[ |
Not enough room on stack for results |
[ |
Fewer than 2 operands on stack |
[ |
Either operand is not a string |
1.9. Implementation Notes
-
Returns substrings that share the original string value
-
Search is performed byte-by-byte
-
Efficient for small search patterns
-
Empty seek always matches at position 0
1.10. Performance Considerations
-
Linear search - O(n*m) worst case
-
Fast for typical use cases
-
For repeated searches, consider preprocessing
-
Finding all occurrences requires loops
1.11. Advanced Example
/findall { % string pattern => array-of-positions
[
3 1 roll % [ string pattern
0 % [ string pattern position
{
2 copy search {
% [ ... string pattern pos post match pre true
pop pop % [ ... string pattern pos post
3 index length % [ ... string pattern pos post len
4 index length sub % [ ... string pattern pos post (string.len - post.len)
4 -1 roll pop % [ ... string pattern (string.len - post.len) pos
add % [ ... string pattern new-pos
dup % [ ... string pattern pos pos
4 -1 roll exch % [ ... pos string pattern pos
} {
pop exit % [ ... string pattern pos
} ifelse
} loop
pop pop pop % [ positions...
]
} def
(the cat and the dog) (the) findall % [0 13]
1.12. See Also
-
anchorsearch- Test for prefix match -
token- Parse token from string -
getinterval- Extract substring