我有以下字串,我想從中提取任何不包含數字或特殊字符的“單詞”。目前,接受逗號、問號或句號:
b? Dl )B 4(V! A. MK, YtG ](f 1m )CNxuNUR {PG?
期望的輸出:
b? Dl A. MK, YtG
5
電流輸出:
b? Dl A. MK, YtG 1m
6
目前,下面的函式成功地從字串中洗掉了數字,但是,同時包含數字和字母的單詞不會被省略。因此,'1m' 包含在我當前的輸出中。
當前功能:
def howMany(sentence)
if sentence.is_a? String
output = sentence.split
count = 0
test_output = []
output.each {|word|
if word !~ /\D/ || word =~ /[!@#$%^&*()_ {}\[\]:;'"\/\\><]/
count
else
test_output.push(word)
count = 1
end
}
puts test_output
puts count
else
puts "Please enter a valid string"
end
end
我的假設是我必須以某種方式遍歷字串中的每個單詞才能找到它是否包含數字,但是,我不確定如何進行該特定解決方案。我想過.split("")在我的output.each函式內部使用,但嘗試了幾次后沒有成功。
任何建議將不勝感激。
提前致謝!
uj5u.com熱心網友回復:
這是String#scan使用正則運算式的作業。
str = "b? Dl )B 4(V! A. MK, YtG ](f 1m )CNxuNUR {PG?"
str.scan(/(?<!\S)[a-z.,\?\r\n] (?!\S)/i)
#=> ["b?", "Dl", "A.", "MK,", "YtG"]
Ruby 演示 < ˉ\ (ツ) /ˉ > PCRE 演示
我已經包含了regex101.com的鏈接,這是一個用于測驗正則運算式的流行站點,因為它提供了大量資訊,特別是通過將滑鼠懸停在運算式的每個元素上,可以獲得對其功能的解釋。(即通過將游標懸停。)由于該站點不支持 Ruby 的正則運算式引擎(v2.0 的Onigmo),我選擇了 PCRE 正則運算式引擎,在這種情況下,它給出的結果與 Ruby 的引擎相同。
正則運算式可以以自由間距模式撰寫,以使其自記錄。
/
(?<!\S) # negative lookbehind asserts that the following
# match is not preceded by a character other than
# a whitespace
[a-z.,\?\r\n] # match one or more of the indicated characters
(?!\S) # negative lookahead asserts that the previous
# match is not followed by a character other than
# a whitespace
/ix # case-insensitive (i) and free-spacing regex
# definition modes
另外,為了避免需要對負回顧后 (?<!\S)和負先行 (?!\S),一個可能分裂,然后選擇:
a.select { |s| s.match?(/\A[a-z.,\?\r\n] \z/i) }
#=> ["b?", "Dl", "A.", "MK,", "YtG"]
uj5u.com熱心網友回復:
我建議嘗試這樣的事情。
使用 split 將句子轉換為陣列sentence.split(' ')。然后只允許使用匹配模式的那些filter
然后對兩個 puts 操作使用過濾串列。它應該看起來像這樣。
def how_many(sentence)
sentence.split(' ').filter { |word| matches_pattern?(word) }.tap do |words|
puts words.size
puts words # or words.join(' ')
end
end
def matches_pattern?(word)
word.matches? /some_regular_expression/
end
您當然可以相應地進行修改以添加任何側面案例等。這將是一個更慣用的解決方案。
請注意,您也可以使用,.filter(&method(:matches_pattern?))但這可能會讓某些人感到困惑。
編輯:rubular.com 是嘗試您的正則運算式的好地方。
編輯:當事情變得困難時,嘗試將它們分成較小的塊(即盡量不要使方法長于 5 行)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/340794.html
