大写每个编号行的第一个字母

时间:2015-02-01 22:43:31

标签: ruby

我无法弄清楚如何跳过这些数字(例如1.,2.,3。)。我不应该修改字符串,但仍需要将每行的所有首字母大写(忽略数字)。也许我可以使用each_linesub,也许match方法。

1.     i was just doing this problem.
2. also eating so much food.
3.     it was nice listening to the Mahler.

1.     I was just doing this problem.
2. Also eating so much food.
3.     It was nice listening to the Mahler.

3 个答案:

答案 0 :(得分:2)

您可以使用gsub更新多行:

str = <<TEXT
1.     i was just doing this problem.
2. also eating so much food.
3.     it was nice listening to the Mahler.
TEXT

puts str.gsub(/^(\d+\.[ \t]+)(\w)/) { "#{$1}#{$2.upcase}" }

输出:

1.     I was just doing this problem.
2. Also eating so much food.
3.     It was nice listening to the Mahler.
  • ^匹配行的开头
  • (\d+\.[ \t]+)捕获编号行的开头,即一个或多个数字,后跟一个文字点和空格/制表符
  • (\w)捕获单个字符

第一个捕获组未经修改返回:#{$1},而第二个捕获组是upcased:#{$2.upcase}

由于upcase仅影响字母,您还可以upcase包括第一个字母在内的所有内容:

puts str.gsub(/^\d+\.[ \t]+\w/, &:upcase)

答案 1 :(得分:1)

使用匹配前和匹配后变量

可能有更有效的方法来执行此操作,但一种简单的方法是使用pre-matchpost-match特殊变量来打印每行的未修改部分,同时仍然调用String#upcase在它的第一封信上。例如:

text = <<'EOF'
1.     i was just doing this problem.
2. also eating so much food.
3.     it was nice listening to the Mahler.
EOF

text.each_line { |line| line =~ /\p{Alpha}/; print $`, $&.upcase, $' }

这将正确打印:

1.     I was just doing this problem.
2. Also eating so much food.
3.     It was nice listening to the Mahler.

,同时仍然返回原始的未经修改的字符串:

  

#=&GT; “1.我只是在做这个问题。\ n2。还吃了那么多食物。\ n3。听马勒很好听。\ n”

答案 2 :(得分:1)

可以预测,修改后的字符串是保留的,所以我建议像:

str=
%{1.     i was just doing this problem.
2. also eating so much food.
3.
4.     It was nice listening to the Mahler.}

new_str = str.each_line.map { |l| l.sub(/[a-z]/i) { |c| c.upcase } }.join
puts new_str
  # 1.     I was just doing this problem.
  # 2. Also eating so much food.
  # 3.
  # 4.     It was nice listening to the Mahler.

这不会改变str

puts str
  # 1.     i was just doing this problem.
  # 2. also eating so much food.
  # 3.
  # 4.     It was nice listening to the Mahler.

或者,您可以添加捕获组并在块中引用其值:

str.each_line.map { |l| l.sub(/([a-z])/i) {  $1.upcase } }.join
相关问题