|
9 | 9 | public import Init.Data.String.Pattern |
10 | 10 | public import Init.Data.Ord.Basic |
11 | 11 | public import Init.Data.Iterators.Combinators.FilterMap |
| 12 | +public import Init.Data.String.ToSlice |
12 | 13 |
|
13 | 14 | set_option doc.verso true |
14 | 15 |
|
@@ -36,6 +37,12 @@ public section |
36 | 37 |
|
37 | 38 | namespace String.Slice |
38 | 39 |
|
| 40 | +instance : HAppend String String.Slice String where |
| 41 | + -- This implementation performs an unnecessary copy which could be avoided by providing a custom |
| 42 | + -- C++ implementation for this instance. Note: if `String` had no custom runtime representation |
| 43 | + -- at all, then this would be very easy to get right from Lean using `ByteArray.copySlice`. |
| 44 | + hAppend s t := s ++ t.copy |
| 45 | + |
39 | 46 | open Pattern |
40 | 47 |
|
41 | 48 | /-- |
@@ -349,6 +356,28 @@ Examples: |
349 | 356 | def dropPrefix [ForwardPattern ρ] (s : Slice) (pat : ρ) : Slice := |
350 | 357 | dropPrefix? s pat |>.getD s |
351 | 358 |
|
| 359 | +/-- |
| 360 | +Constructs a new string obtained by replacing all occurrences of {name}`pattern` with |
| 361 | +{name}`replacement` in {name}`s`. |
| 362 | +
|
| 363 | +This function is generic over all currently supported patterns. The replacement may be a |
| 364 | +{name}`String` or a {name}`String.Slice`. |
| 365 | +
|
| 366 | +Examples: |
| 367 | +* {lean}`"red green blue".toSlice.replace 'e' "" = "rd grn blu"` |
| 368 | +* {lean}`"red green blue".toSlice.replace (fun c => c == 'u' || c == 'e') "" = "rd grn bl"` |
| 369 | +* {lean}`"red green blue".toSlice.replace "e" "" = "rd grn blu"` |
| 370 | +* {lean}`"red green blue".toSlice.replace "ee" "E" = "red grEn blue"` |
| 371 | +* {lean}`"red green blue".toSlice.replace "e" "E" = "rEd grEEn bluE"` |
| 372 | +* {lean}`"aaaaa".toSlice.replace "aa" "b" = "bba"` |
| 373 | +* {lean}`"abc".toSlice.replace "" "k" = "kakbkck"` |
| 374 | +-/ |
| 375 | +def replace [ToForwardSearcher ρ σ] [ToSlice α] (s : Slice) (pattern : ρ) (replacement : α) : |
| 376 | + String := |
| 377 | + (ToForwardSearcher.toSearcher s pattern).fold (init := "") (fun |
| 378 | + | sofar, .matched .. => sofar ++ ToSlice.toSlice replacement |
| 379 | + | sofar, .rejected start stop => sofar ++ s.replaceStartEnd! start stop) |
| 380 | + |
352 | 381 | /-- |
353 | 382 | Removes the specified number of characters (Unicode code points) from the start of the slice. |
354 | 383 |
|
|
0 commit comments