验证字符串仅包含 Ruby 中允许的字符 [英] Validate that string contains only allowed characters in Ruby

查看:37
本文介绍了验证字符串仅包含 Ruby 中允许的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试一个 Ruby 字符串是否只包含一组特定的字符?

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

例如,如果我允许的字符集是 "AGHTM" 加上数字 0-9

For example, if my set of allowed characters is "AGHTM" plus digits 0-9,

  • 字符串"MT3G22AH" 有效;

字符串"TAR34" 无效(因为R).

推荐答案

这似乎比之前所有的基准测试都要快(by @Eric Duminil)(ruby 2.4):

This seems to be faster than all previous benchmarks (by @Eric Duminil)(ruby 2.4):

!string.match?(/[^AGHTM0-9]/) 

这篇关于验证字符串仅包含 Ruby 中允许的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆