繁体   English   中英

如何在Ruby中检查单词的第一个和最后一个字符是否相同?

[英]How to check if the first and last character of a word are the same in Ruby?

如果我有一个句子字符串,我想检查每个单词的第一个和最后一个字母是否相同,并找出哪个单词的第一个和最后一个字母相同。 例如:

sentence_one = "Label the bib numbers in red."

您可以使用正则表达式:

sentence_one = "Label the bib numbers in red"

sentence_one.scan(/(\b(\w)\w*(\2)\b)/i)
#=> [["Label", "L", "l"], ["bib", "b", "b"]]

\\b是单词边界, \\w与字母匹配(您可能需要对此进行调整)。 有3个捕获项:(1)整个单词,(2)第一个字母,(3)最后一个字母。 使用\\2要求最后一个字母与第一个字母匹配。

这将打印出所有以相同字母开头和结尾的单词(不区分大小写)

sentence_one = "Label the bib numbers in red"
words = sentence_one.split(' ')

words.each do |word|
  if word[0].downcase == word[-1].downcase
    puts word
  end
end

在评论中,OP询问如何获得具有所需属性的单词数。 这是一种方法。 我假设期望的属性是单词的第一个和最后一个字符相同,尽管可能大小写不同。 这是一种不产生将对其元素进行计数的中间数组的方法。

r = /
    \b            # match a word break
    (?:           # begin a non-capture group
      \p{Alpha}   # match a letter
      |           # or
      (\p{Alpha}) # match a letter in capture group 1
      \p{Alpha}*  # match zero or more letters
      \1          # match the contents of capture group 1
    )             # end the non-capture group
    \b            # match a word break
    /ix           # case-indifferent and free-spacing regex definition modes

str = "How, now is that a brown cow?"

str.gsub(r).count
  #=> 2

请参阅String#gsub ,特别是只有一个参数且没有提供块的情况。

注意

str.gsub(r).to_a
  #=> ["that", "a"]

str.scan(r)
  #=> [["t"], [nil]]

有时,当正则表达式包含捕获组时,使用scan会很尴尬(请参阅String#scan )。 通常可以通过使用gsub后跟to_a (或Enumerable#entries )来避免这些问题。

sentence_one.scan(/\S+/).select{|s| s[0].downcase == s[-1].downcase}
# => ["Label", "bib"]
sentence_one = "Label the bib numbers in red"
puts sentence_one.split(' ').count{|word| word[0] == word[-1]} # => 1

只是添加一个选项更多的拆分到数组(跳过一个字母的单词):

sentence_one =  "Label the bib numbers in a red color"

sentence_one.split(' ').keep_if{ |w| w.end_with?(w[0].downcase) & (w.size > 1) }

#=> ["Label", "bib"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM