Home
Ruby
String Between, Before, After
Updated Apr 5, 2023
Dot Net Perls
Between, before, after. 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.
Method notes. 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.
String index
Substring
Method examples. Here we consider the 3 custom defs written in the Ruby language. We use substring syntax (which is like string slices) to return values.
Detail We call index() and must test for a nil result value—this occurs if the substring was not found.
Important We should add in the length of the left part to ensure we skip past the left part within the source string.
Tip Before and 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
Notes, results. 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.
A summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 5, 2023 (simplify).
Home
Changes
© 2007-2025 Sam Allen