I need to grab a string like
"/html/body/a"
i need to check the last portion, in this case "a" after the final "/"
how can i do this ? how can i regex match for the last item after the final "/" ?
x = "/html/body/a"
x.split("/").last # => "a"
Regex? Not sure, but what's wrong with
my_string.split("/").last # Maybe you want some error checking here, I don't know.
If you want to use regexp, this would be it:
mystring = "/html/body/a"
if mystring =~ /([^\/]+)$/
last_part = $1
end
Related
For example I have url string like:
https://abc.s3-something.amazonaws.com/subfolder/1234/5.html?X-Amz-Credential=abcd12bhhh34-1%2Fs3%2Faws4_request&X-Amz-Date=2016&X-Amz-Expires=3&X-Amz-SignedHeaders=host&X-Amz-Signature=abcd34hhhhbfbbf888ksdskj
From this string I need to extract number 1234 which comes after subfolder/. I tried with gsub but no luck. Any help would be appreciated.
Suppose your url is saved in a variable called url.
Then the following should return 1234
url.match(/subfolder\/(\d*)/)[1]
Explanation:
url.match(/ # call the match function which takes a regex
subfolder\/ # search for the first appearance of the string 'subfolder/'
# note: we must escape the `/` so we don't end the regex early
(\d*) # match any number of digits in a capture group,
/)[1] # close the regex and return the first capture group
lwassink has the right idea, but it can be done more simply. If subfolder is always the same:
url = "https://abc.s3-something.amazonaws.com/subfolder/1234/5.html?X-Amz-Credential=abcd12bhhh34-1%2Fs3%2Faws4_request&X-Amz-Date=2016&X-Amz-Expires=3&X-Amz-SignedHeaders=host&X-Amz-Signature=abcd34hhhhbfbbf888ksdskj"
url[/subfolder\/\K\d+/]
# => "1234"
The \K discards the matched text up to that point, so only "1234" is returned.
If you want to get the number after any subfolder, and the domain name is always the same, you might do this instead:
url[%r{amazonaws\.com/[^/]+/\K\d+}]
# => "1234"
s.split('/')[4]
Add a .to_i at the end if you like.
Or, to key it on a substring like you asked for...
a = s.split '/'
a[a.find_index('subfolder') + 1]
Or, to do it as a one-liner I suppose you could:
s.split('/').tap { |a| #i = 1 + a.find_index('subfolder')}[#i]
Or, since I am a damaged individual, I would actually write that:
s.split('/').tap { |a| #i = 1 + (a.find_index 'subfolder')}[#i]
url = 'http://abc/xyz'
index= url.index('/abc/')
url[index+5..length_of_string_you_want_to_extract]
Hope, that helps!
I am trying to find a string in a sentence
/a.**117228558440230**.24692.116944575135295/65456
want the string after a and before first . in ruby on rails
thanks in advance
One way is to find the "a." then capture everything until the next "." like this:
result = sentence =~ /a\.(.*?)\./ && $1
You can do that with a simple regexp:
string = '/a.117228558440230.24692.116944575135295/65456'
regexp = /\D\.(\d*)\./
regexp.match(string)[1]
#=> "117228558440230"
You can also give a try to this
str = "/a.**117228558440230**.24692.116944575135295/65456"
str[/\D\.(\d*)\./]
=> "*.24692."
This methods gives you the string if available in the sentence otherwise nil
I am having one string variable need to check substring is present in it, like:
str = "sdfgg"
need to check if str contains df
Please help me to write a code in ruby to check the scenario
Use String#include?.
str.include?("df")
You can also use a regex for that:
if str =~ /df/
# Successful match
else
# Match attempt failed
end
How do I remove a substring after a certain character in a string using Ruby?
new_str = str.slice(0..(str.index('blah')))
I find that "Part1?Part2".split('?')[0] is easier to read.
I'm surprised nobody suggested to use 'gsub'
irb> "truncate".gsub(/a.*/, 'a')
=> "trunca"
The bang version of gsub can be used to modify the string.
str = "Hello World"
stopchar = 'W'
str.sub /#{stopchar}.+/, stopchar
#=> "Hello W"
A special case is if you have multiple occurrences of the same character and you want to delete from the last occurrence to the end (not the first one).
Following what Jacob suggested, you just have to use rindex instead of index as rindex gets the index of the character in the string but starting from the end.
Something like this:
str = '/path/to/some_file'
puts str.slice(0, str.index('/')) # => ""
puts str.slice(0, str.rindex('/')) # => "/path/to"
We can also use partition and rpartitiondepending on whether we want to use the first or last instance of the specified character:
string = "abc-123-xyz"
last_char = "-"
string.partition(last_char)[0..1].join #=> "abc-"
string.rpartition(last_char)[0..1].join #=> "abc-123-"
string =
"
[title]
{snippet}
[something else in bracket]
{something else}
more text
#tags
"
I want to delete first occurrence of [] and {}
s.clean_method or regexp should return string like that
"
title
snippet
[something else in bracket]
{something else}
more text
#tags
"
Language Ruby 1.9.2
You need String#sub (not gsub):
irb> "[asd]{asd}[asd]{asd}".sub(/\[(.+?)\]/,'\1').sub(/\{(.+?)\}/,'\1')
=> "asdasd[asd]{asd}"
More of the same:
s = "[asd]{asd}[asd]{asd}"
%w({ } [ ]).each{|char| s.sub!(char,'')}
#=> "asdasd[asd]{asd}"
Well, if that's all you want to do, all you need to do is
result = string.sub('{', '').sub('[', '').sub('}', '').sub(']', '')
Of course, that's a terribly inelegant solution, and doesn't consider things like unmatched brackets, etc.
A better solution would probably be:
pattern1 = /\{(.*?)\}/
pattern2 = /\[(.*?)\]/
match1 = pattern1.match(string)
result = string.sub(match1[0], match1[1])
match2 = pattern2.match(result)
result = result.sub(match2[0], match2[1])
This could probably be simplified, but that's what comes off the top of my head :)
BTW, if you want to replace all instances, all you need to do is use gsub instead of sub