-
-
Save nedzadarek/828cff5b24dae68b2a81f7193623c55d to your computer and use it in GitHub Desktop.
`replace` with parse rule for string replacement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Red [] | |
replace': func [ | |
"Replaces values in a series, in place" | |
series [series!] "The series to be modified" | |
pattern "Specific value or parse rule pattern to match" | |
value "New value, replaces pattern in the series" | |
/all "Replace all occurrences, not just the first" | |
/deep "Replace pattern in all sub-lists as well" | |
/local p rule s e many? len pos | |
][ | |
if system/words/all [deep any-list? series] [ | |
pattern: to block! either word? p: pattern [to lit-word! pattern] [pattern] ; `p` is not used | |
parse series rule: [ | |
some [ | |
s: pattern e: ( | |
s: change/part s value e | |
unless all [return series] | |
) :s | |
| ahead any-list! into rule | skip | |
] | |
] | |
return series | |
] | |
if system/words/all [char? :pattern any-string? series] [ | |
pattern: form pattern | |
] | |
; toomasv addition 13.03.2018 --> | |
either system/words/all [any-string? :series block? :pattern] [ | |
; changed 2 lines: if `value` is a function | |
p: compose [to pattern change pattern] | |
; parse series either all [[some p ]][ p] | |
; if `pattern` contains `set`, `copy` etc then `value` should be evaluated after parssing | |
parse series either all [[some to pattern ]] compose [to pattern change (value)] | |
][ ;<-- toomasv addition | |
many?: any [ | |
system/words/all [series? :pattern any-string? series] | |
binary? series | |
system/words/all [any-list? series any-list? :pattern] | |
] | |
len: either many? [length? pattern] [1] | |
either all [ | |
pos: series | |
either many? [ | |
while [pos: find pos pattern] [ | |
remove/part pos len | |
pos: insert pos value | |
] | |
] [ | |
while [pos: find pos :pattern] [ | |
pos: insert remove pos value | |
] | |
] | |
] [ | |
if pos: find series :pattern [ | |
remove/part pos len | |
insert pos value | |
] | |
] | |
] | |
series | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@nedzadarek I don't understand, what do you think this (line 33) should do: