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
Related
I have a string as given below,
./component/unit
and need to split to get result as component/unit which I will use this as key for inserting hash.
I tried with .split(/.\//).last but its giving result as unit only not getting component/unit.
I think, this should help you:
string = './component/unit'
string.split('./')
#=> ["", "component/unit"]
string.split('./').last
#=> "component/unit"
Your regex was almost fine :
split(/\.\//)
You need to escape both . (any character) and / (regex delimiter).
As an alternative, you could just remove the first './' substring :
'./component/unit'.sub('./','')
#=> "component/unit"
All the other answers are fine, but I think you are not really dealing with a String here but with a URI or Pathname, so I would advise you to use these classes if you can. If so, please adjust the title, as it is not about do-it-yourself-regexes, but about proper use of the available libraries.
Link to the ruby doc:
https://docs.ruby-lang.org/en/2.1.0/URI.html
and
https://ruby-doc.org/stdlib-2.1.0/libdoc/pathname/rdoc/Pathname.html
An example with Pathname is:
require 'pathname'
pathname = Pathname.new('./component/unit')
puts pathname.cleanpath # => "component/unit"
# pathname.to_s # => "component/unit"
Whether this is a good idea (and/or using URI would be cool too) also depends on what your real problem is, i.e. what you want to do with the extracted String. As stated, I doubt a bit that you are really intested in Strings.
Using a positive lookbehind, you could do use regex:
reg = /(?<=\.\/)[\w+\/]+\w+\z/
Demo
str = './component'
str2 = './component/unit'
str3 = './component/unit/ruby'
str4 = './component/unit/ruby/regex'
[str, str2, str3, str4].each { |s| puts s[reg] }
#component
#component/unit
#component/unit/ruby
#component/unit/ruby/regex
mystring = "svn-myapplication" or mystring = "git-myapplication"
My desired output:
mystring = "myapplications(svn)"
mystring = "myapplication(git)"
Question: The first 3 characters of the string should be moved to the last with enclosed brackets and the "-" should be removed.
I tried to do something like this:
mystring.gsub('svn-','')+"(svn)" but svn might be git, so i want to use the first three characters to be moved to end with "-" removed and brackets enclosed
A regular expression with groups would work well:
mystring.gsub(/^([a-z]+)-(\w+)/, '\2(\1)')
Lets rock'n'roll :)
mystring = "svn-myapplication"
mystring.split('-').rotate.join('(') + ')'
You could use e regular expression but the simplest solution is as follows
mystring = "svn-myapplication"
puts "#{mystring[4..-1]}(#{mystring[0..2]})"
gives
myapplication(svn)
You can use the [] method of Ruby's String class for this:
mystring = "svn-myapplication"
mystring = "#{mystring[4..-1]}(#{mystring[0,3]})"
You can try something like this in irb
1.9.3-p362 :001 > mystring = "svn-myapplication"
1.9.3-p362 :002 > mystring.gsub(mystring[0,3]+'-','')+(mystring[0,3])
I was going to submit this but, at least I can see how to do it better!
def test(s = '')
match = /\w+-/.match(s).to_s
match = match[0..-2]
s.gsub!(/\w+-/, '')
s << "(#{match})"
end # of test
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
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