Ruby regex find and replace a number inside a string - ruby-on-rails

How would I find and replace '49' when '49' will be an unknown id, using ruby on rails?
str = "select * from clients where client_id = 49 order by registration_date asc"
str = str.gsub(/someRegExThatFinds49/, replacement_id) # <------ Here's the concept
Looking for a syntax and example that's correct. Thanks.

This would work, using a copy of the string:
new_str = str.gsub(/\d+/, replacement_id)
Or, if you prefer to do it in place (modifying the string directly)
str.gsub!(/\d+/, replacement_id)
ian.

unknown_id = 49
puts "hello4849gone".gsub(/#{unknown_id}/, "HERE") #=> hello48HEREgone

str = str.gsub(/49/, replacement_id)
Or use the self-updating version:
str.gsub!(/49/, replacement_id)
Also, check out Rubular which allows you to test out regular expressions.

Related

¿Add [""] to ruby string?

How can I convert this:
https://myimage.com
to this in ruby?
["https://myimage.com"]
I've tried with join with no luck...
Thanks
It's not very clear what you're looking to accomplish. You can't really turn https://myimage.com into anything, since it is not valid Ruby syntax.
However, if you first have it as a string, then you can easily put it inside of an array like this:
url = 'https://myimage.com'
result = [url]
puts result.inspect
#=> ["https://myimage.com"]
Or if instead you want a string as your result, then here yah go:
url = 'https://myimage.com'
result = '["' + url + '"]'
puts result
#=> ["https://myimage.com"]

Getting substring value in Chef ruby

I have a string that has the following value:
ucp-1.1.0_dtr-2.0.0
I am trying to fetch only 1.1.0 from the string. I am using the following code but it doesn't seem to work
substring = ucp-1.1.0_dtr-2.0.0.gsub('ucp-','')
String's [] and a simple regex will do it:
'ucp-1.1.0_dtr-2.0.0'[/[\d.]+/] # => "1.1.0"
This works because the search will stop as soon as it matches, so the first occurrence wins resulting in 1.1.0.
If you wanted the second/last occurrence then adding $ tells the regex engine to only look at the end of the line for the matching pattern:
'ucp-1.1.0_dtr-2.0.0'[/[\d.]+$/] # => "2.0.0"
The Regexp documentation covers all this.
substring = "ucp-1.1.0_dtr-2.0.0".gsub('ucp-','').split("_").first untried.
using regex with ruby string methods you can achieve this..
"ucp-1.1.0_dtr-2.0.0"
version = "ucp-1.1.0_dtr-2.0.0".scan(/[0-9_]/).join(".").split("_").first.slice(0..-2)
Or with your code you can try this..
substring = "ucp-1.1.0_dtr-2.0.0".gsub('ucp-','').split("_").first
Try this (verified):
"ucp-1.1.0_dtr-2.0.0".match(/^.-(.)_.-.$/)[1]

Remove double backslash from string with Ruby

I have the following string:
string = "\"2014\\/jul\\/grandes\\/volvo-s-60-d5-momentum-1403253_2.jpg\""
that I want to gsub into this string:
string = "2014/jul/grandes/volvo-s-60-d5-momentum-1403253_2.jpg"
Here is how I thought it should work:
string.gsub(/\\./,'')
but this returns:
"\"2014julgrandesvolvo-s-60-d5-momentum-1403253_3.jpg\""
What am I doing wrong?
You have a “dot” in regexp for no reason. Instead of:
string.gsub(/\\./,'')
try:
string.gsub(/["\\]/,'')
Or, credits to #sawa, try this instead:
string.tr('"\\','')
Or, credits to #Chirantan:
string.delete('"\\')
Benchmarks: http://gist.github.com/dominikh/208915
string.delete('\\\"')
is one possible solution. But I'm sure there are better ones out there.
Another nasty one using String#[]= method. This is just for fun :-
string[/["\\]/] = '' until string[/["\\]/].nil?
# or
string[/["\\]/] = '' while string =~ /["\\]/
But #gsub is better way to solve this. If you don't want to modify the original string, then use String#slice instead of String#[]=. That's it.

Regex extract substring ruby

"{\"status\":1,\"redirect\":\"/some/uri/uri2/index.html?post_login=80607979823520\",\"security_token\":\"/cpsess8233434446\"}"
I am getting this response as string and I need to extract security_token value.
I tried to convert the string to Hash by eval method.seems not worked and I need to do a regex match.
You can do this:
require 'json'
a = JSON.load "{\"status\":1,\"redirect\":\"/some/uri/uri2/index.html?post_login=80607979823520\",\"security_token\":\"/cpsess8233434446\"}"
p a["security_token"] #=> "/cpsess8233434446"
You need to parse the JSON data..
result = "{\"status\":1,\"redirect\":\"/some/uri/uri2/index.html?post_login=80607979823520\",\"security_token\":\"/cpsess8233434446\"}"
h = JSON.parse(result)
h['security_token'] # => "/cpsess8233434446"
You can either JSON.load the data and filter for ['security_token'] or use a .match(/security_token/) style regex expression.
I'd suggest the prior for future readability and code maintenance.

string manipulation in ruby on rails

I have a string of the format,
/d.phpsoft_id=369242&url=http://f.1mobile.com/mobile_software/finance/com.mshift.android.achieva_2.apk
and i need to edit this string using regular expression that the result string should start from http: ie the resultatnt string should be
http://f.1mobile.com/mobile_software/finance/com.mshift.android.achieva_2.apk
please help
For these types of situations, I prefer to go with readily available tools that will help provide a solution or at the very least will point me in the right direction. My favourite for regex is txt2re because it will output example code in many languages, including ruby.
After running your string through the parser and selecting httpurl for matching, it output:
txt='/d.phpsoft_id=369242&url=http://f.1mobile.com/mobile_software/finance/com.mshift.android.achieva_2.apk'
re1='.*?' # Non-greedy match on filler
re2='((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s"]*))' # HTTP URL 1
re=(re1+re2)
m=Regexp.new(re,Regexp::IGNORECASE);
if m.match(txt)
httpurl1=m.match(txt)[1];
puts "("<<httpurl1<<")"<< "\n"
end
str = "/d.phpsoft_id=369242&url=http://f.1mobile.com/mobile_software/finance/com.mshift.android.achieva_2.apk"
str.spl­it("url=")­[1]
Simple Answer
You need to do following
str = "/d.phpsoft_id=369242&url=http://f.1mobile.com/mobile_software/finance/com.mshift.android.achieva_2.apk"
start=str.index('http://')
resultant=str[start,str.length]

Resources