2014-12-24 19 views
1

我有一句話說:沒有在一句影響換句話說空格打破擠壓話

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

從「狐狸」中我們可以預計什麼? – Toto

+0

@ M42我會指望它是'狐狸跳起來......' –

+0

那麼聚合字母的規則是什麼?爲什麼'狐狸'變成'狐狸'而不是'狐狸'? – Toto

回答

2

這裏有一個短的一個

(?:(?<=\s\w)|(?<=^\w))\s(?=\w\W) 

用空字符串替換匹配。

Demo

這是基於這樣的假設,即永遠不會有兩個單字符單詞相鄰。如果它發現這樣的事情,它會刪除中間的空間。

如果你想獲得幻想,你可以阻止它拿起I a,如Am I a good programmer?,並從串聯中的小寫和大寫字母:

(?:(?<=\s\w)|(?<=^\w))\s+(?=[a-z]\W)(?!(?<=I\s)a) 

Demo

+1

正是......--) https://regex101.com/r/cB2uL9/4 –

+1

@EddieB:謝謝,回答更新。 –

2
(?<=\s[a-zA-Z])\s(?=[a-zA-Z]\s[a-zA-Z]|[a-zA-Z](?:$|\.)) 

試試這個。更換empty string。參見demo。

https://regex101.com/r/gQ3kS4/15

+0

對不起,總是很挑剔,但如果第二個字符是空格,例如,這不起作用。 'T h e' - >'T he'。 –

+0

@正確的權利!!!!! :P – vks

+0

@vks你絕對做得很好......但你需要排除「我和A」......英語中唯一的單字母單詞。 (?![ia]) –