Get Substring Between Two Strings Or Characters In Ruby

Posted by Weston Ganger on May 03, 2015

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:

Posted in Rails and Tagged with rails ruby regex substring 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts