我有这样一句话:
The fox j u m p e d over the big b r o w n boar !
我想将其更改为:
The fox jumped over the big brown boar !
(注意 - 空格在中间时被压扁,但留在完整的单词和感叹号之间)
我写这段代码是为了这样做:
str = 'The fox j u m p e d over the big b r o w n boar !'
prev_char = '0'
prev_prev_char = '0'
next_next_char = '0'
new_str = ''
(0..(str.length)).each do |index|
t_char = str[index]
prev_char = index > 0 ? str[index-1] : '0'
prev_prev_char = index > 1 ? str[index-2] : '0'
next_next_char = index-1 < str.length ? str[index+2] : '0'
new_str = "#{new_str}#{t_char}" unless t_char == ' ' && prev_char != ' ' && prev_prev_char == ' ' && next_next_char == ' '
end
results = new_str.split(' ').join(' ')
p (results == 'The fox jumped over the big brown boar !')
但我确信有更好或更聪明的方法。有什么建议吗?
答案 0 :(得分:2)
(?<=\s[a-zA-Z])\s(?=[a-zA-Z]\s[a-zA-Z]|[a-zA-Z](?:$|\.))
试试这个。empty string
。见。演示。
答案 1 :(得分:2)