thesis
thesis

Reputation: 2575

How to split string into 2 parts after certain position

For example I have some random string:

str = "26723462345"

And I want to split it in 2 parts after 6-th char. How to do this correctly?

Thank you!

Upvotes: 22

Views: 24260

Answers (6)

Jordan Running
Jordan Running

Reputation: 106147

Here’s on option. Be aware, however, that it will mutate your original string:

part1, part2 = str.slice!(0...6), str

p part1  # => "267234"
p part2  # => "62345"
p str    # => "62345"

Update

In the years since I wrote this answer I’ve come to agree with the commenters complaining that it might be excessively clever. Below are a few other options that don’t mutate the original string.

Caveat: This one will only work with ASCII characters.

str.unpack("a6a*")
# => ["267234", "62345"]

The next one uses the magic variable $', which returns the part of the string after the most recent Regexp match:

part1, part2 = str[/.{6}/], $'
p [part1, part2]
# => ["267234", "62345"]

And this last one uses a lookbehind to split the string in the right place without returning any extra parts:

p str.split(/(?<=^.{6})/)
# => ["267234", "62345"]

Upvotes: 13

jaynetics
jaynetics

Reputation: 1313

_, part1, part2 = str.partition /.{6}/

https://ruby-doc.org/core-1.9.3/String.html#method-i-partition

Upvotes: 5

Nick McD.
Nick McD.

Reputation: 137

The best way IMO is string.scan(/.{6}/)

irb(main)> str
=> "abcdefghijklmnopqrstuvwxyz"
irb(main)> str.scan(/.{13}/)
=> ["abcdefghijklm", "nopqrstuvwxyz"]

Upvotes: 4

antinome
antinome

Reputation: 3458

As a fun answer, how about:

str.split(/(^.{1,6})/)[1..-1]

This works because split returns the capture group matches, in addition to the parts of the string before and after the regular expression.

Upvotes: 1

fullstackplus
fullstackplus

Reputation: 1071

Here's a reusable version for you:

str       = "26723462345"
n         = str.length
boundary  = 6
head      = str.slice(0, boundary) # => "267234" 
tail      = str.slice(boundary, n) # => "62345" 

It also preserves the original string, which may come in handy later in the program.

Upvotes: 0

Yule
Yule

Reputation: 9774

This should do it

[str[0..5], str[6..-1]]

or

 [str.slice(0..5), str.slice(6..-1)]

Really should check out http://corelib.rubyonrails.org/classes/String.html

Upvotes: 46

Related Questions