Regular expressions are a terse way to do certain simple string processing tasks. For example, to replace all instances of foo
in one string with bar
, the following can be used:
R/ foo/ "bar" re-replace
That could be done with sequence operations, but consider doing this replacement for an arbitrary number of o's, at least two:
R/ foo+/ "bar" re-replace
operator matches one or more occurrences of the previous expression; in this case o
. Another useful feature is alternation. Say we want to do this replacement with fooooo or boooo. Then we could use the code
R/ (f|b)oo+/ "bar" re-replace
To search a file for all lines that match a given regular expression, you could use code like this:
"file.txt" ascii file-lines [ R/ (f|b)oo+/ re-contains? ] filter
To test if a string in its entirety matches a regular expression, the following can be used:
USE: regexp "fooo" R/ (b|f)oo+/ matches? .
Regular expressions can't be used for all parsing tasks. For example, they are not powerful enough to match balancing parentheses.