我正在尝试确定输入字符串是否只包含字符G,C,T或A.我提供的字符串可以包含任意数量的字符。如果字符串包含除指定字符以外的任何字符,我应该返回""。
我已经看过几个解决方案,我可以验证字符串只包含数字或字母但是如何在执行代码块之前验证字符串是否只包含特定的字母字符?
示例:
答案 0 :(得分:3)
input = "ACGTCTTAA"
if input =~ /\A[GCTA]+\z/
# put your code here
end
这意味着任何succession of 'G', 'C', 'T' or 'A's from the beginning to the end of the string
。
如果可以接受空字符串,则可以改为使用/\A[GCTA]*\z/
。
您还可以删除每个'G','C','T'和'A'与String#delete,并检查字符串是否为空:
"C".delete("GCTA").empty? #=> true
"ACGTXXXCTTAA".delete("GCTA").empty? #=> false
"ACGTCTTAA".delete("GCTA").empty? #=> true
"".delete("GCTA").empty? #=> true
答案 1 :(得分:0)
您可以使用正则表达式进行检查 - 例如
puts 'run code' if 'C' =~ /^[GCTA]+$/
其中:
^ = start of line
$ = end of line
[] = match any character within
+ = one or more of previous
答案 2 :(得分:0)
这可能是您正在寻找的解决方案。
"C".match(/^[GCTA]+$/) => #<MatchData "C">
"ACGTXXXCTTAA".match(/^[GCTA]+$/) => nil
答案 3 :(得分:0)
非正则表达式回答:
nucleic_acid_sequence = ['G','C','T','A']
test_input = 'GFWG'
unless (test_input.chars-nucleic_acid_sequence).any?
puts 'valid input!'
end