ruby split string by repeating characters or a space
split
will just use whatever it matches as a delimiter, removing it from the string in question. What you're looking for is scan
:
str = "6885558 8866887777"
str.scan(/((\d)\2*)/).map(&:first)
# => ["6", "88", "555", "8", "88", "66", "88", "7777"]
Taking it slow, the \d
matches any digit. It's in the second capturing group, so \2*
then matches any further occurrences of the same digit. This produces an array that looks like
[["6", "6"], ["88", "8"], ["555", "5"], ["8", "8"],
["88", "8"], ["66", "6"], ["88", "8"], ["7777", "7"]]
Since we only want the first item in each of those sub arrays, we can collect them all with map(&:first)
.
(Note that str.scan(/(\d)\1*/)
would simply produce an array out of the first capturing group, which means we'd only get one digit from a sequence of possibly repeated numbers.)
How to split the string by certain amount of characters in Ruby
Using Enumerable#each_slice
'some_string'.chars.each_slice(3).map(&:join)
# => ["som", "e_s", "tri", "ng"]
Using regular expression:
'some_string'.scan(/.{1,3}/)
# => ["som", "e_s", "tri", "ng"]
Split string in ruby when character is different to previous character
Here is a one liner using chunk, map and join:
"aabbbc226%%*".chars.chunk(&:itself).map{|_,c| c.join}
# => ["aa", "bbb", "c", "22", "6", "%%", "*"]
Split string by whitespaces, ignoring escaped whitespaces
If your strings have no escape sequences, you may use a splitting approach with
.split(/(?<!\\)\s+/)
Here, (?<!\\)\s+
matches 1+ whitespaces (\s+
) that are not preceded with \
.
If your strings may contain escape sequences, a matching approach is preferable as it is more reliable:
.scan(/(?:[^\\\s]|\\.)+/)
See the Ruby demo.
It will match 1 or more characters other than \
and whitespace (with [^\\\s]
) and any escape sequence (matched with \\.
, a backslash + any char other than line break chars).
To get rid of \
symbols, you will have to use a gsub
later.
Split string from the second occurrence of the character
You could use regular expression matching:
str = "20050451100_9253629709-2-2"
m = str.match /(.+)-(\d+)/
[m[1], m[2]] # => ["20050451100_9253629709-2", "2"]
The regular expression matches "anything" followed by a dash followed by number digits.
Splitting with empty space in Ruby
From string#split documentation, emphasis my own:
split(pattern=$;, [limit])
If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.
If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.
If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ' were specified.
If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.
So if you were to use " x ".split(/[ ]+/, -1)
you would get your expected result of ["", "x", ""]
*edited to reflect Wayne's comment
How do I remove repeated spaces in a string?
>> str = "foo bar bar baaar"
=> "foo bar bar baaar"
>> str.split.join(" ")
=> "foo bar bar baaar"
>>
Split a string with multiple delimiters in Ruby
What about the following:
options.gsub(/ or /i, ",").split(",").map(&:strip).reject(&:empty?)
- replaces all delimiters but the
,
- splits it at
,
- trims each characters, since stuff like
ice cream
with a leading space might be left - removes all blank strings
Why does Ruby String#split not treat consecutive trailing delimiters as separate entities?
You need to pass a negative value as the second parameter to split
. This prevents it from suppressing trailing null fields:
"w$x$$\r\n".chomp.split('$', -1)
# => ["w", "x", "", ""]
See the docs on split
.
Ruby regex for a split every four characters not working
Try scan
instead:
$ irb
>> "abcd1234beefcake".scan(/..../)
=> ["abcd", "1234", "beef", "cake"]
or
>> "abcd1234beefcake".scan(/.{4}/)
=> ["abcd", "1234", "beef", "cake"]
If the number of characters isn't divisible by 4, you can also grab the remaining characters:
>> "abcd1234beefcakexyz".scan(/.{1,4}/)
=> ["abcd", "1234", "beef", "cake", "xyz"]
(The {1,4}
will greedily grab between 1 and 4 characters)
Related Topics
Ruby on Rails: Yielding Specific Views in a Specific Places in the Layout
Polymorphic Association with Multiple Associations on the Same Model
Using Multiple Controllers in One View in Rails
Paperclip Amazon S3 Setup with Heroku
What Does the Underscore Mean in Literal Numbers
If Else Statements in .Html.Erb in Views
Creating a Hash with Values as Arrays and Default Value as Empty Array
Are There Better Ways to Prevent 'Yield' When No Block Is Passed In
Missing a Template for This Request Format and Variant
Rails Before_Filter for Specific Actions in Controller
Accepts_Nested_Attributes_For Rails 4 Is Not Deleting
Verb-Agnostic Matching in Sinatra
How to Run Ruby 2.0 with Jruby 1.7
What Is a Worker in Ruby/Rails
How to Force One Field in Ruby's CSV Output to Be Wrapped with Double-Quotes
How to Find a Model's Relationships
Ruby: Build Failed (Macos 11.2 Using Ruby-Build 20210119) MAC Big Sur