Get Substring Between Two Strings Or Characters In Ruby

Posted by Weston Ganger

Commonly you may want to get a substring between to strings or characters in Ruby. I found it a little more difficult to find this information than it should have been.

str = "your +example string@ here"

# Between 1st + and 1st @:
regex = /\+(.*?)@/

# Between 1st + and last @:
regex = /\+(.*)@/

# Between last + and last @:
regex = /.*\+(.*)@/

# Between last + and 1st @:
regex = /.*\+(.*?)@/

# Fetch the value
str[regex, 1]
# or 
str.slice(regex, 1)

Related External Links:

Article Topic:Software Development - Rails

Date:May 03, 2015

Recommended Posts



Send Me A Message

I would love to get in touch and talk about your next project. Feel free to send a message and I will get back to you shortly.

Get Connected