2017-01-01 28 views
-1

我想確定一個輸入字符串是否只包含字符G,C,T或A.我提供的字符串可以包含任意數量的這些字符,可以按任意順序排列。如果字符串包含除指定的字符以外的任何字符,則應返回「」。我如何驗證一個字符串只包含Ruby中的特定字母字符?

我見過幾種解決方案,我可以驗證一個字符串只包含數字或字母,但是如何在執行代碼塊之前驗證字符串是否只包含特定的字母字符?

實施例:

  • INPUT_1 = 「C」
  • Result_1 =運行的代碼塊
  • INPUT_2 = 「ACGTXXXCTTAA」
  • Result_2 =不運行代碼塊
+2

請參考[Tour](https://stackoverflow.com/tour)。你有什麼嘗試?我不知道紅寶石,但由於它不被認爲是一種深奧的語言,這應該是簡單的*如果你有任何線索你在做什麼。 –

回答

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 
0

您可以使用正則表達式來檢查 - 類似於

puts 'run code' if 'C' =~ /^[GCTA]+$/ 

其中:

^ = start of line 
$ = end of line 
[] = match any character within 
+ = one or more of previous 
+0

允許多個字符的編輯答案 –

+0

當不存在匹配時返回'nil',即使OP詢問沒有匹配時返回空字符串,這也是一個好主意。 –

0

這可能是你正在尋找的解決方案。

"C".match(/^[GCTA]+$/) => #<MatchData "C"> 
"ACGTXXXCTTAA".match(/^[GCTA]+$/) => nil 
+0

「ACGTXXX \ nCTTAA」呢? –

+0

然後最好使用 「ACGTXXX \ nCTTAA」.match(/ \ A [GCTA] + \ z /) – Ondemannen

0

非-regexp回答:

nucleic_acid_sequence = ['G','C','T','A'] 

test_input = 'GFWG' 

unless (test_input.chars-nucleic_acid_sequence).any? 
    puts 'valid input!' 
end 
相關問題