Here we consider the 3 custom defs written in the Ruby language. We use substring syntax (which is like string slices) to return values.
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