Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all substrings that match a pattern in Rebol

Tags:

regex

rebol

Here, I'm attempting to find all matches of a pattern in a string:

theString: "There is a blue truck and a red car next to an orange building."
thePattern: [["blue" | "red" | "orange"] ["truck" | "car" | "building"]]
print parse thePattern theString

Instead of returning["red truck" "blue car" "orange building"], the parse function returns false.

Does Rebol have any functions that can be used to find all matches of a pattern in a string, similar to the regular expression matching functions of other programming languages?

like image 807
Anderson Green Avatar asked Sep 05 '25 17:09

Anderson Green


1 Answers

You can try this:

string: "There is a blue truck and a red car next to an orange building."
pattern: [
    ["blue" | "red" | "orange"] 
    space
    ["truck" | "car" | "building"]
]

parse string [
    some [
        copy value pattern (print value)
    |   skip    
    ]
]

which prints:

blue truck
red car
orange building

skip is used to move to next character when the pattern is not matched. Also space is added to the pattern as it's not "bluetruck" or "redcar".

Parenthesis are used to execute Rebol code inside parse rules, so you can replace print with something else there (like append block value etc.)

like image 187
rebolek Avatar answered Sep 07 '25 18:09

rebolek