Return index of all occurrences of a character in a string in ruby
s = "a#asg#sdfg#d##"
a = (0 ... s.length).find_all { |i| s[i,1] == '#' }
Find all indices of a substring within a string
The standard hack is:
indices = "Einstein".enum_for(:scan, /(?=in)/).map do
Regexp.last_match.offset(0).first
end
#=> [1, 6]
Get the index of all characters in ruby
Use Enumerator#with_index
:
str = "sssaadd"
str.each_char.with_index do |char, index|
puts "#{index}: #{char}"
end
How to get indexes of all occurrences of a pattern in a string
You can use .scan
and $`
global variable, which means The string to the left of the last successful match, but it doesn't work inside usual .scan
, so you need this hack (stolen from this answer):
string = "Jack and Jill went up the hill to fetch a pail of water. Jack fell down and broke his crown. And Jill came tumbling after. "
string.to_enum(:scan, /(jack|jill)/i).map do |m,|
p [$`.size, m]
end
output:
[0, "Jack"]
[9, "Jill"]
[57, "Jack"]
[97, "Jill"]
UPD:
Note the behaviour of lookbehind – you get the index of the really matched part, not the look one:
irb> "ab".to_enum(:scan, /ab/ ).map{ |m,| [$`.size, $~.begin(0), m] }
=> [[0, 0, "ab"]]
irb> "ab".to_enum(:scan, /(?<=a)b/).map{ |m,| [$`.size, $~.begin(0), m] }
=> [[1, 1, "b"]]
How do I find the index of a character in a string in Ruby?
index(substring [, offset]) → fixnum or nil
index(regexp [, offset]) → fixnum or nil
Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.
"hello".index('e') #=> 1
"hello".index('lo') #=> 3
"hello".index('a') #=> nil
"hello".index(?e) #=> 1
"hello".index(/[aeiou]/, -3) #=> 4
Check out ruby documents for more information.
Finding # occurrences of a character in a string in Ruby
I was able to solve this by passing a string through scan
as shown in another answer.
For example:
string = 'This is an example'
puts string.count('e')
Outputs:
2
I was also able to pull the occurrences by using scan and passing a sting through instead of regex which varies slightly from another answer but was helpful in order to avoid regex.
string = 'This is an example'
puts string.scan('e')
Outputs:
['e','e']
I explored these methods further in a small video guide I created after I figured it out.
How do I find the index in a string of where my nth occurrence of a regex ends?
From my comments that grew from a link to a related question:
The answer to that question
"abc12def34ghijklmno567pqrs".to_enum(:scan, /\d+/).map { Regexp.last_match }
Can easily be adapted to get the MatchData for a single item
string.to_enum(:scan, regex).map { Regexp.last_match }[n - 1].offset(0)
to find the n
th match in a string.
Search string returning indexes of all overlapping occurrences for multiple variable length Ruby regular expressions
Matches can't overlap. Use zero-length assertions instead:
guilty_terms = [/danger/i, /hack/i, /ckdd/i]
# the positive lookahead is where the magic happens
regex_guilty_terms = /(?=(#{Regexp.union(guilty_terms)}))/
evidence = "hackddangerhackdanger"
# just a squeezin'
[].tap { |arr| evidence.scan(regex_guilty_terms) { |x| arr << [$1, $~.begin(1)] } }
# => [["hack", 0], ["ckdd", 2], ["danger", 5], ["hack", 11], ["danger", 15]]
The position 13 is not printed because it's not actually a match, so... not sure how you'd get the expected results :)
Related Topics
Rails with Ruby-Debugger Throw 'Symbol Not Found: _Ruby_Current_Thread (Loaderror)'
Why Do I Get Uninitialized Constant Devise Name Error When Running Webrick Server
Keep Form Fields Filled After an Error (Ror)
Using Memcache Client with Ruby
How to Sort a Ruby Hash by Number Value
Removing All Empty Elements from a Hash/Yaml
Redefining a Single Ruby Method on a Single Instance with a Lambda
Installing Ruby on MAC Os X 10.8.2
Rails - Sort by Join Table Data
Do Ruby 'Require' Statements Go Inside or Outside the Class Definition
Split String into a List, But Keeping the Split Pattern