Ruby:每 X 个字符插入一个空格 [英] Ruby: Insert spaces every X number of characters

查看:41
本文介绍了Ruby:每 X 个字符插入一个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ruby​​ 字符串中,如何每 X 个字符插入一个空格?

In a ruby string, how can I insert a space every X number of characters?

例如,我想在给定字符串的每 8 个字符处插入一个空格.

As an example, I'd like to insert a space every 8 characters of a given string.

推荐答案

>> s = "1234567812345678123456781234567812345678"
=> "1234567812345678123456781234567812345678"
>> s.gsub(/(.{8})/, '\1 ')
=> "12345678 12345678 12345678 12345678 12345678 "

您可以使用正向前瞻来避免在末尾添加额外的空格:

You could use positive lookahead to avoid adding an extra space at the end:

>> s.gsub(/(.{8})(?=.)/, '\1 \2')
=> "12345678 12345678 12345678 12345678 12345678"

这篇关于Ruby:每 X 个字符插入一个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆