1

我有一个变量address,它现在是一个包含一些不必要信息的长字符串,例如:"Aboriginal Relations 11th Floor Commerce Place 10155 102 Street Edmonton AB T5J 4G8 Phone 780 427-9658 Fax 780 644-4939 Email gerry.kushlyk@gov.ab.ca"

Aboriginal Relations在一个名为 的变量title中,我正在尝试调用address.gsub!(title,''),但它返回原始字符串。

我也试过address.gsub!(/#{title}/,'')address.gsub!("#{title}",'')但那些也行不通。有任何想法吗?

对不起,当我将它输入堆栈溢出时发生了错字,下面是代码和输出,复制并粘贴:

(这是在一个循环中,所以会有多个输出)

p title
address.gsub!(title,'')
p address

输出

"Aboriginal Relations "
"Aboriginal Relations 11th Floor Commerce Place 10155 102 Street Edmonton AB T5J 4G8 Phone         780 427-9658 Fax 780 644-4939 Email gerry.kushlyk@gov.ab.ca"
"Aboriginal Tourism Advisory Council "
"Aboriginal Tourism Advisory Council 5th Floor Terrace Building 9515 107 Street Edmonton AB T5K 2C3 Phone 780 427-9687 Fax 780 422-7235 Email foip.fintprccs@gov.ab.ca"
"Acadia Foundation "
"Acadia Foundation PO Box 96 Oyen AB T0J 2J0 Phone 403 664-3384 Fax 403 664-3316 Email acadiafoundation@telus.net"
"Access Advisory Council "
"Access Advisory Council 12th Floor Centre West Building 10035 108 Street Edmonton AB T5J 3E1 Phone 780 427-2805 Fax 780 422-3204 Email barb.joyner@gov.ab.ca"
"ACCM Benevolent Association "
"ACCM Benevolent Association Suite 100 9403 95 Avenue Edmonton AB T6C 4M7 Phone 780 468-4648 Fax 780 468-4648 Email accmmanor@shaw.ca"
"Acme Municipal Library "
"Acme Municipal Library PO Box 326 Acme AB T0M 0A0 Phone 403 546-3845 Fax 403 546-2248 Email aamlibrary@marigold.ab.ca"

同样,如果我尝试,address.match(/#{title}/)我会得到零。

4

2 回答 2

1

我假设您使用的是 ruby​​ 1.9 或更高版本。尾随空格可能是不间断空格:

p "Relations\u00a0"  # looks like a trailing space, but strip won't remove it

摆脱它:

"Relations\u00a0".gsub!(/^\u00a0|\u00a0$/, '')  # => "Relations"

所有 unicode 空白的更通用的解决方案:

"Relations\u00a0".gsub!(/^[[:space:]]|[[:space:]]$/, '')  # => "Relations"

要查看您的角色是什么:

title[-1].ord  # => 160 (example only)
'%x' % title[-1].ord  # => "a0" (hex equivalent; example only)
于 2013-07-05T19:30:57.763 回答
0

title = title[0..-2]似乎解决了它。出于某种原因stripchomp将无法正常工作。

于 2013-07-05T19:15:22.303 回答