ruby - 如何编写一个方法,它接受一个数字并返回一个字符串,在每个奇数之前和之后放置一个连字符?

标签 ruby regex

一个异常(exception)是返回的字符串不能以连字符开头或结尾,并且每个奇数数字前后只允许有一个单个连字符。例如:

def hyphenate(number)
  # code
end

hyphenate(132237847) # should return "1-3-22-3-7-84-7"

"-1-3-22-3-7-84-7-"  # incorrect because there is a hyphen before and after
                     # each beginning and ending odd digit respectively.

"1--3-22-3--7-84-7" # Also incorrect because there is more than one
                    # single hyphen before and after each odd digit

最佳答案

我建议匹配一个非单词边界 \B (这将匹配两个数字之间的位置) 后面或前面有一个奇数:

number.to_s.gsub(/\B(?=[13579])|\B(?<=[13579])/, '-')

由于相同的位置不能匹配两次,因此避免了连续连字符的问题。

rubular demo

with the replacement

关于ruby - 如何编写一个方法,它接受一个数字并返回一个字符串,在每个奇数之前和之后放置一个连字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459441/

相关文章:

ruby - 如何从数组中提取特定元素?

regex - 如何使用grep提取子字符串?

带有排除字符的正则表达式和另一个正则表达式

ruby-on-rails - 为什么没有 `self` 就不能更新 ActiveRecord 模型中的关联属性?

ruby - 可能对 curry 过程进行 instance_eval 吗?

c# - C# 'using' 语句的 Ruby 等价物

ruby-on-rails - 自定义设计 Controller 不工作

php - 如何拆分文本以匹配双引号加上尾随文本以点?

RegEx:如果某个字符在引号内,则不匹配它

regex - 如何使用正则表达式在软件源中搜索特定的包? [Ubuntu]