使用ruby删除特定字符串(电子邮件地址)中的所有空格

时间:2015-04-03 22:27:39

标签: ruby string gsub

用户可以输入文本,但是我摄取数据的方式通常包含不必要的回车和空格。

要删除那些使输入看起来更像真正的句子,我使用以下内容:

string.delete!("\n")
string = string.squeeze(" ").gsub(/([.?!]) */,'\1  ')

但在以下情况下,我在电子邮件中收到了一个意想不到的空间:

string = "Hey     what is \n\n\n up joeblow@dude.com      \n okay"

我得到以下内容:

"Hey what is up joeblow@dude.  com okay"

如何为字符串的电子邮件部分启用例外,以便我得到以下内容:

"Hey what is up joeblow@dude.com okay"

2 个答案:

答案 0 :(得分:3)

<强>被修改

您的方法执行以下操作:

 string.squeeze(" ") # replaces each squence of " " by one space
 gsub(/([.?!] */, '\1 ') # check if there is a space after every char in the between the brackets [.?!]
                         # and whether it finds one or more or none at all
                         # it adds another space, this is why the email address
                         # is splitted

我猜你真正想要的是,如果标点符号后面没有空格,请添加一个空格。你可以这样做。

string.gsub(/([.?!])\W/, '\1 ') # if there is a non word char after 
                                # those punctuation chars, just add a space

然后你只需要用一个空格替换每个空间字符序列。所以最后的解决方案是:

string.gsub(/([.?!])(?=\W)/, '\1 ').gsub(/\s+/, ' ')
# ([.?!]) => this will match the ., ?, or !. and capture it
# (?=\W) => this will match any non word char but will not capture it.
# so /([.?!])(?=\W)/ will find punctuation between parenthesis that
# are followed by a non word char (a space or new line, or even 
# puctuation for example).
# '\1 ' => \1 is for the captured group (i.e. string that match the 
# group ([.?!]) which is a single char in this case.), so it will add 
# a space after the matched group.

答案 1 :(得分:0)

如果你可以摆脱挤压声明,那么使用Nafaa的答案是最简单的方法,但我已经列出了另一种方法,以防它有用:

string = string.split(" ").join(" ")

但是,如果你想保留那个挤压声明,你可以修改Nafaa的方法并在挤压声明后使用它:

string.gsub(/\s+/, ' ').gsub('. com', '.com')

或直接更改字符串:

string.gsub('.  com', '.com')