Validate that string contains only allowed characters in Ruby

前端 未结 4 1598
情深已故
情深已故 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:57

    A nicely idiomatic non-regex solution is to use String#count:

    "MT3G22AH".count("^AGHTM0-9").zero?  # => true
    "TAR34".count("^AGHTM0-9").zero?     # => false
    

    The inverse also works, if you find it more readable:

    "MT3G22AH".count('AGHTM0-9') == "MT3G22AH".size  # => true
    

    Take your pick.

    For longer strings, both methods here perform significantly better than regex-based options.

提交回复
热议问题