HomeSearch

Ruby String Between, Before, After

Develop methods to find substrings between other substrings and before and after other substrings.

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.Strings

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.index, rindexSubstring

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.

Between: 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.

Ruby program that implements between, before, after 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, "=") Output 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.

And: The results from the Ruby implementation here match the results from the other implementations on this site.

Between, Before, After

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.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.