Suppose we want to parse a string
written in a simple computer language. We want to extract a substring between a start and end character.
With between()
we can invoke index and rindex()
on a string
, and then take a substring in between. Some logic and testing is needed for correctness.
Here we consider the 3 custom defs written in the Ruby language. We use substring syntax (which is like string
slices) to return values.
index()
and must test for a nil
result value—this occurs if the substring was not found.string
.after()
are implemented in similar ways to between()
. We use index()
and rindex()
to search strings.def between(value, left, right) # Search from the start. pos1 = value.index(left) return "" if pos1 == nil pos1 += left.length # Search from the end. pos2 = value.rindex(right) return "" if pos2 == nil # Return a substring. return value[pos1, pos2 - pos1] end def before(value, test) # Search from the start. pos1 = value.index(test) return "" if pos1 == nil return value[0, pos1] end def after(value, test) # Search from the end. pos1 = value.rindex(test) return "" if pos1 == nil pos1 += test.length return value[pos1..-1] end input = "DEFINE:A=TWO" # Test between method. puts between(input, "DEFINE:", "=") puts between(input, ":", "=") # Test before method. puts before(input, ":") puts before(input, "=") # Test after method. puts after(input, ":") puts after(input, "DEFINE:") puts after(input, "=")A A DEFINE DEFINE:A A=TWO A=TWO TWO
When we examine the input string, we see that it contains syntax like a computer language. By calling between, before and after on this string
, we test correctness.
To develop these 3 methods, we use index()
and rindex()
to search strings, and substring syntax to take parts of strings. We extract relative parts of strings.