To get a substring between two specific characters in Ruby, you can use a regular expression with the scan
method or the match
method of the String class.
In this example,
str
with a value of "(Hello) World!"
./\((.*?)\)/
uses the escaped parentheses \(
and \)
to match the literal '(' and ')' characters. The .*?
is a non-greedy match for any characters between them.scan
method on str
with the defined pattern to find all matches. The scan
method returns an array of all matching substrings.str = "(Hello) World!"
pattern = /\((.*?)\)/
substring = str.scan(pattern).flatten.first
puts "Substring between '(' and ')' is: #{substring}"
Substring between '(' and ')' is: Hello
In this example,
str
with a value of "Ruby [is] awesome!"
./\[(.*?)\]/
uses the escaped square brackets \[
and \]
to match the literal '[' and ']' characters. The .*?
is a non-greedy match for any characters between them.scan
method on str
with the defined pattern to find all matches. The scan
method returns an array of all matching substrings.str = "Ruby [is] awesome!"
pattern = /\[(.*?)\]/
substring = str.scan(pattern).flatten.first
puts "Substring between '[' and ']' is: #{substring}"
Substring between '[' and ']' is: is
In this example,
str
with a value of "Find {the} substring"
./\{(.*?)\}/
uses the escaped curly braces \{
and \}
to match the literal '{' and '}' characters. The .*?
is a non-greedy match for any characters between them.scan
method on str
with the defined pattern to find all matches. The scan
method returns an array of all matching substrings.str = "Find {the} substring"
pattern = /\{(.*?)\}/
substring = str.scan(pattern).flatten.first
puts "Substring between '{' and '}' is: #{substring}"
Substring between '{' and '}' is: the
In this tutorial, we learned How to get Substring between two Specific Characters in Ruby language with well detailed examples.