re = /^(?(DEFINE)(?'longitude'[-+]?(?|180(?>\.0+)?|(?>1[0-7]\d|[1-9]?\d)(?>\.\d+)?))(?'latitude'[-+]?(?|90(?>\.0+)?|[1-8]?\d(?>\.\d+)?)))LINESTRING\s*\((?>(?:(?(?<=\()(?>\s*)|(?>\s*,\s*))(?P>longitude)(?>\s*)(?P>latitude)\s*){2,})\)$/
str = 'LINESTRING(-5.764642842113973 41.915708669165184 ,-5.7630935311317435 41.91684083791108,-5.765079036355018 41.918309783201565,-5.765336528420449 41.918293068151534,-5.765593685209751 41.91818504391658,-5.7656215131282815 41.91791859998719,-5.764469504356383 41.916424697127816,-5.764911398291588 41.91594194048126 , -5.764642842113973 41.915708669165184 )'
subst = ''
result = str.sub(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