string manipulation in ruby on rails - 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]

Related

ruby substring backslash plus "

So, I have a string like this:
str1 = "blablablabla... original_url=\"https://facebook.com/125642\"> ... blablablabla..."
what is the best approach to extract this original_url?
what I have done so far is this:
original_url = str1['content'][str1['content'].index('original_url')+12..str1['content'].index('>')-2]
it works, but it seems such like a poor solution, mostly I'm stuggling to find this substring /">
here's what I have tried so far
str1.index('\">')
str1.index('\\">') # escaping only one backslach
str1.index('\\\">') # escaping both back slash and "
str1.index("\\\">") # was just without idea over here
I'm not a ruby programmer, so I'm kinda lost here
The best approach to parse xml namespaces is to use Nokogiri as suggested by #spickermann.
Quick but not elegant and not even efficient solutions:
str1 = "blablablabla... original_url=\"https://facebook.com/125642\"> ... blablablabla..."
original_url=str1[str1.index("original_url")+14...str1.index("\">")]
# => "https://facebook.com/125642"
original_url=str1.split(/original_url=\"/)[1].split(/">/).first
# => "https://facebook.com/125642"

#HttpContext.Current.User.Identity.Name not showing backslash

Super Simple. Only issues I find are people getting null. Which I obvi fixed. But where is the backslash???!!
params.me = '#HttpContext.Current.User.Identity.Name';
This returns
"domainUserName" <- Browser
"domain\\UserName" <- Debugging
What I expect is
"domain\UserName" <- Browser
Any ideas?
Based on your comments you are using the following code to show the user name:
alert('#HttpContext.Current.User.Identity.Name');
#HttpContext.Current.User.Identity.Nameis a string that can contain "\" backslash character. This character is considered as a escape character in javascript as it is in C# as well.
You need to escape the "\" character in the string before passing it to Javascript like that:
alert('#HttpContext.Current.User.Identity.Name.Replace("\\", "\\\\")')

ruby regex with quotes

I'm trying to pass more than one regex parameter for parts of a string that needs to be replaced. Here's the string:
str = "stands in hall "Let's go get to first period everyone" Students continue moving to seats."
Here is the expected string:
str = "stands in hall "Let's go get to first period everyone" Students continue moving to seats."
This is what I tried:
str.gsub(/'|"/, "'" => "\'", """ => "\"")
This is what I got:
"stands in hall \"Let's go get to first period everyone\" Students continue moving to seats."
How do I get the quotes in while sending in two regex parameters using gsub?
This is an HTML unescaping problem.
require 'cgi'
CGI.unescape_html(str)
This gives you the correct answer.
From my comments on this question:
Your updated version is correct. The only reason the slashes are in your final line of code is that it's an escape sequence so that you don't mistakenly think the first slash is used to terminate the string. Try assigning your output and printing it:
str1 = str.gsub(/'|"/, "'" => "\'", """ => "\"")
puts str1
and you'll see that the slashes are gone when str1 is printed using puts.
The difference is that autoevaluating variables within irb (which is what I assume you're doing to execute this sample code) automatically calls the inspect method, which for string variables shows the string in its entirety.
Because I did not understand unescaping characters I found an alternative solution that might be the "rails-way"
Can you use <%= raw 'some_html' %>
My final solution ended up being this instead of messy regex and requiring CGI
<%= raw evidence_score.description %>
Unescaping HTML string in Rails

NSString to NSDictionary

I have a string (from HTTP Header) and want to split it into a dictionary.
foo = \"bar\",baz=\"fooz\", beta= \"gamma\"
I ca not guarantee that the string is the same every time. Maybe there are spaces, maybe not, sometimes the double quotes are escaped, sometimes not.
So I found the solution in PHP with regular expressions. Unfortunately I can't convert it to work on iOS.
preg_match_all('#('.$key.')=(?:([\'"])([^\2]+?)\2|([^\s,]+))#', $input, $hits, PREG_SET_ORDER);
foreach ($hits as $hit) {
$data[hit[1]] = $hit[3] ? $hit[3] : $hit[4];
}
Can anybody help me converting this to Objective-C?
I met a guy which is kinda RegEx guru. He explained the whole stuff and I got the following (working!!!!) solution in RegEx.
This gives me strings like foo="bar":
(?<=[,\\s])((realm|qop|nonce|opaque)=(?:([\"'])([^\2]+?)\2|([^\\s,]+)))
I then use another RegEx to split it by key and value to create a dictionary.

How do I scan url for a specific string with spaces and special characters?

I'm using stringscanner on my request URL in order to get the name of the user's currently selected category, but I've been having difficulty dealing with spaces and special characters.
request.url.scan(/\?category=\w+/).to_s.gsub('?category=', '')
URL examples followed by result
http://localhost:3000/search?category=dog&search=&utf8=%E2%9C%93 => ["dog"]
http://localhost:3000/search?category=dog.com&search=&utf8=%E2%9C%93 => ["dog"]
http://localhost:3000/search?category=dog+cat&search=&utf8=%E2%9C%93 => ["dog"]
I'm trying to get ["dog"] ["dog.com"] and ["dog cat"], but am currently stuck. Any ideas?
Note: Considering removing spaces from categories and replacing them with dashes as multiple spaces could be problematic, but if it's possible to create one function to rule them all, that would be awesome.
This is Rails, is there a reason you're not just using params[:category]?
If you are trying to extract params then you could use parse_query :
uri = "http://localhost:3000/search?category=dog+cat&search=&utf8=%E2%9C%93"
result = Rack::Utils.parse_query(URI(uri).query) #=> {"category"=>"dog cat", "search"=>"", "utf8"=>"\xE2\x9C\x93"}
result["category"] #=> dog cat

Resources