re = /^.*osf=(\S+?)[;|\s].*$/m
str = 'osf=5633d9e768732dc8c7ca1f9a._7iTy0uvL_4eVBf_y_SzRVEeOII; csrftoken=ah8zV0tSZSx9nnmkMqOKaUARdWC2OTWs
asdf=asdfasdf; osf=5633d9e768732dc8c7ca1f9a._7iTy0uvL_4eVBf_y_SzRVEeOII; csrftoken=ah8zV0tSZSx9nnmkMqOKaUARdWC2OTWs
asfdasdf=asdfasdf; osf=5633d9e768732dc8c7ca1f9a._7iTy0uvL_4eVBf_y_SzRVEeOII
osf=5633d9e768732dc8c7ca1f9a._7iTy0uvL_4eVBf_y_SzRVEeOII
'
subst = '\\1'
result = str.gsub(re, subst)
# Print the result of the substitution
puts result
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html