![](/img/trans.png)
[英]Using regex to strip all characters and punctuation from a string except apostrophe
[英]Trying to remove punctuation without using regex
我試圖從不使用正則表達式的單詞數組中刪除標點符號。 在下面,例如
str = ["He,llo!"]
我想要:
result # => ["Hello"]
我試過了:
alpha_num="abcdefghijklmnopqrstuvwxyz0123456789"
result= str.map do |punc|
punc.chars {|ch|alpha_num.include?(ch)}
end
p result
但是它返回["He,llo!"]
沒有任何更改。 無法找出問題所在。
include?
塊返回true/false
,請嘗試使用select
函數過濾非法字符。
result = str.map {|txt| txt.chars.select {|c| alpha_num.include?(c.downcase)}}
.map {|chars| chars.join('')}
p result
str=["He,llo!"]
alpha_num="abcdefghijklmnopqrstuvwxyz0123456789"
程序
v=[]<<str.map do |x|
x.chars.map do |c|
alpha_num.chars.map.include?(c.downcase) ? c : nil
end
end.flatten.compact.join
光伏
產量
["Hello"]
exclusions = ((32..126).map(&:chr) - [*'a'..'z', *'A'..'Z', *'0'..'9']).join
#=> " !\"\#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
arr = ['He,llo!', 'What Ho!']
arr.map { |word| word.delete(exclusions) }
#=> ["Hello", "WhatHo"]
如果您可以使用正則表達式並且真正只想刪除標點符號,則可以編寫以下內容。
arr.map { |word| word.gsub(/[[:punct:]]/, '') }
#=> ["Hello", "WhatHo"]
參見String#delete 。 請注意, arr
不會被修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.