Home
Map
String Between, Before, AfterDevelop methods to find substrings between other substrings and before and after other substrings.
Ruby
This page was last reviewed on Apr 5, 2023.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 5, 2023 (simplify).
Home
Changes
© 2007-2024 Sam Allen.