Rails

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 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts