2011-01-11 5 views
26

정규 표현식에 익숙하지 않았기 때문에 어떻게하는지 잘 모르겠습니다.이를 수행하는 적절한 방법을 찾지 못했지만 문자열 (모든 탭 및 줄 바꿈 포함)Ruby는 모든 공백을 단일 공백으로 줄입니다.

1/2 cup 




      onion   
      (chopped) 

모든 공백을 제거하고 각 공백을 하나의 공백으로 바꿀 수 있습니까?

str.squeeze([other_str]*) → new_str 
Builds a set of characters from the other_str parameter(s) using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character. 

    "yellow moon".squeeze     #=> "yelow mon" 
    " now is the".squeeze(" ")   #=> " now is the" 
    "putters shoot balls".squeeze("m-z") #=> "puters shot balls" 

답변

53

이것은 당신이 공백 문자 같은 전체 클래스를 치료와 함께 공백의 조합의 실행을 대체하기를 원하기 때문에 정규 표현식이 잘 작동 경우는 다음과 같습니다

+1

정답입니다. . :) –

8

당신은 스퀴즈 방법을 원하는 단일 공백 ​​문자. 해당 문자열이 s에 저장되어있는 경우, 당신은 할 것이다 그래서 :

fixed_string = s.gsub(/\s+/, ' ') 
+1

이것은 적절하지 않다고 생각합니다. 탭의 실행을 단일 탭으로 압축하고 개행을 단일 개행으로 압축합니다. 내가 읽었을 때, 문제는 공백 문자 조합을 하나의 공백 문자로 대체하는 방법을 모색하는 것이다. – Chuck

+0

너무'String.squeeze'는 regex를 인자로 받아들이지 않습니다. Upvote 당신이 좋은 생각이 될 것이라고 생각한다면; PR을 제출할 수 있습니다. – the911s

+2

또한 중복 된 항목을 제거합니다. "class"는 "clas"가되어 html을 실행하면 deal breaker가 될 수 있습니다. (레일에있는 경우) 더 적절한 메소드가 String # squish가됩니다. – engineerDave

3

선택한 대답은 non-breaking space 문자를 제거하지 않습니다.

이 1.9에서 작동합니다 :

fixed_string = s.gsub(/(\s|\u00A0)+/, ' ')

+0

나는 여러 개의 공백 문자가 웹 브라우저에 의해 하나의 공백으로 축소되기 때문에 OP가 의미없는 공백 (예 : 둘 이상의 공백 문자를 실행)을 제거하여 HTML 용 문자열의 크기를 줄이려고한다고 가정합니다. 어쨌든 ... 따라서 비공개 공간은 HTML에서는 의미가 없지만 축소되지는 않습니다. 즉, 제거하지 않으려 고합니다. – callum

4

가장 간단한 해결책 gsub(/\s+/, ' ')의 문제가 모든 공간을 대체대로, 아주 느린 것입니다, 그것은 하나의 경우에도. 그러나 일반적으로 단어 사이에는 1 개의 공백이 있고 순차적으로 2 개 이상의 공백이있는 경우에만 수정해야합니다.

더 나은 솔루션은 gsub(/[\r\n\t]/, ' ').gsub(/ {2,}/, ' ') - 당신이 active_support 확장이다 String#squish을 사용할 수 있습니다 레일 내에서 정상적인 공간

def method1(s) s.gsub!(/\s+/, ' '); s end 
def method2(s) s.gsub!(/[\r\n\t]/, ' '); s.gsub!(/ {2,}/, ' '); s end 

Benchmark.bm do |x| 
    n = 100_000 
    x.report('method1') { n.times { method1("Lorem ipsum\n\n dolor \t\t\tsit amet, consectetur\n \n\t\n adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } } 
    x.report('method2') { n.times { method2("Lorem ipsum\n\n dolor \t\t\tsit amet, consectetur\n \n\t\n adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } } 
end;1 

#  user  system  total  real 
# method1 4.090000 0.010000 4.100000 ( 4.124844) 
# method2 1.590000 0.010000 1.600000 ( 1.611443) 
11

먼저 특별 공백을 제거하고 짠다.

require 'active_support' 

s = <<-EOS 
1/2 cup 

      onion 
EOS 

s.squish 
# => 1/2 cup onion 
관련 문제