2011-10-04 119 views
0

我想寫一個腳本,將匹配字符串中的所有單詞,並將刪除所有非字(IE:。[點],&符,冒號等),並將用連字符替換它們。紅寶石:瞭解正則表達式

示例串:
L. L. Cool J & Sons: The Cool Kats

輸出示例:
L-L-Cool-J-Sons-The-Cool-Kats

下面是一些代碼,我有工作:

str = "L. L. Cool J & Sons: The Cool Kats" 
str.scan(/\w+/) 

感謝所有幫助!對於正則表達式,我還是很新的

回答

1

更新:我只注意到了兩個電話可以表示爲一個:

str.gsub(/\W+/, '-') 
=> "L-L-Cool-J-Sons-The-Cool-Kats" 

...這會導致以相同的納倫德拉的答案還是我原來的答覆:

# 1st gsub: replace all non-words with hyphens 
# 2nd gsub: replace multiple hyphens with a single one 
str.gsub(/\W/,'-').gsub(/-+/, '-') 
=> "L-L-Cool-J-Sons-The-Cool-Kats" 
0

對於非單詞字符,您可以使用\W。它應該做你的工作。 \w代表單詞字符。我用紅寶石工作不多,但它應該看起來像這樣 result = subject.gsub(/\W+/, '-')

0
str.gsub(/\W/, '-')   #=> replaces all non-words with space 
          # OR 
str.gsub(/[^A-Za-z\s]/, ' ') #=> replace all non letters/spaces with space 
str.gsub(/\s+/, '-')   #=> replaces all groups of spaces to hypens 

輸入:

L. L. Cool J & Sons: The Cool Kats

輸出:

L-L-Cool-J-Sons-The-Cool-Kats

2

在單行線,找不到非文本的所有位「單詞字符」並用短劃線代替:

str.gsub(/\W+/, '-') 

請注意,「單詞字符」包括數字和下劃線。要只允許您使用以下字母:

str.gsub(/[^A-Za-z]+/, '-')