Validate that string contains only allowed characters in Ruby

前端 未结 4 1619
情深已故
情深已故 2021-01-07 12:13

How can I test whether a Ruby string contains only a specific set of characters?

For example, if my set of allowed characters is \"AGHTM\" plus digits <

4条回答
  •  旧巷少年郎
    2021-01-07 12:50

    allowed = "AGHTM"
    allowed = /\A[\d#{allowed}]+\z/i
    
    "MT3G22AH" =~ allowed #⇒ truthy
    "TAR34" =~ allowed #⇒ falsey
    

提交回复
热议问题