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
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 match the particular word in a string but it is matching the whole string
doc = "<span>Hi welcome to world</span>"
puts doc.match(/<span>(.*?)<\/span>/)
This code prints the whole string
Output:
<span>Hi welcome to world</span>
But i want only
Hi welcome to world
The another problem is that the output for this program is just an integer
doc = "<span>Hi welcome to world</span>"
puts doc =~ (/<span>(.*?)<\/span>/)
Output:
0
You should put first match group:
puts doc.match(/<span>(.*?)<\/span>/)[1]
# => Hi welcome to world
To answer your another question, from documentation:
Match—If obj is a Regexp, use it as a pattern to match against str,and returns the position the match starts, or nil if there is no match.
After matching with a RegEx you can use $1, $2, ... to output matched groups. So you could simply do:
doc.match(/<span>(.*?)<\/span>/)
puts $1
You could take a look at What are Ruby's numbered global variables for a detailed explanation about other variables such as $'.
I need to determine if a given string has the sequence dash-alpha-alpha-dash.
Example strings:
114888-ZV-209897
409-II-224858
86296-MO-184080
2459-ND-217906
What would be the the regex to determine that?
I'm using Ruby 1.9.3, FWIW.
if subject =~ /-[A-Z]{2}-/
# Successful match
else
# Match attempt failed
end
That [A-Z] thingy is a character class.
It's a simple pattern:
/-[A-Z]{2}-/
will do it.
Your regex is available at: http://rubular.com/r/6hn8BLc7rF
For instance:
"114888-ZV-209897"[/-[A-Z]{2}-/]
=> "-ZV-"
So use:
if "114888-ZV-209897"[/-[A-Z]{2}-/] ...
Suppose I have:
foo/fhqwhgads
foo/fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf/bar
And I want to replace everything that follows 'foo/' up until I either reach '/' or, if '/' is never reached, then up to the end of the line. For the first part I can use a non-capturing group like this:
(?<=foo\/).+
And that's where I get stuck. I could match to the second '/' like this:
(?<=foo\/).+(?=\/)
That doesn't help for the first case though. Desired output is:
foo/blah
foo/blah/bar
I'm using Ruby.
Try this regex:
/(?<=foo\/)[^\/]+/
Implementing #Endophage's answer:
def fix_post_foo_portion(string)
portions = string.split("/")
index_to_replace = portions.index("foo") + 1
portions[index_to_replace ] = "blah"
portions.join("/")
end
strings = %w{foo/fhqwhgads foo/fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf/bar}
strings.each {|string| puts fix_post_foo_portion(string)}
I'm not a ruby dev but is there some equivalent of php's explode() so you could explode the string, insert a new item at the second array index then implode the parts with / again... Of course you can match on the first array element if you only want to do the switch in certain cases.
['foo/fhqwhgads', 'foo/fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf/bar'].each do |s|
puts s.sub(%r|^(foo/)[^/]+(/.*)?|, '\1blah\2')
end
Output:
foo/blah
foo/blah/bar
I'm too tired to think of a nicer way to do it but I'm sure there is one.
Checking for the end-of-string anchor -- $ -- as well as the / character should do the trick. You'll also need to make the .+ non-greedy by changing it to .+? since the greedy version will always match right up to the end of the string, given the chance.
(?<=foo\/).+?(?=\/|$)
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