如何检查字符串是否包含 ruby​​ 中的特殊字符 [英] How to check string contains special character in ruby

查看:53
本文介绍了如何检查字符串是否包含 ruby​​ 中的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在ruby中检查字符串是否包含特殊字符.如果我得到正则表达式也没关系.

How to check whether a string contains special character in ruby. If I get regular expression also it is fine.

请告诉我

推荐答案

special = "?<>',?[]}{=-)(*&^%$#`~{}"
regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/

然后您可以使用正则表达式来测试字符串是否包含特殊字符:

You can then use the regex to test if a string contains the special character:

if some_string =~ regex

这看起来有点复杂:这一点发生了什么

This looks a bit complicated: what's going on in this bit

special.gsub(/./){|char| "\\#{char}"

就是转这个

"?<>',?[]}{=-)(*&^%$#`~{}"

进入这个:

"\\?\\<\\>\\'\\,\\?\\[\\]\\}\\{\\=\\-\\)\\(\\*\\&\\^\\%\\$\\#\\`\\~\\{\\}"

这是每个特殊字符,用 \ 转义(它本身在字符串中转义,即 \\ 而不是 \).然后用它来构建一个像这样的正则表达式:

Which is every character in special, escaped with a \ (which itself is escaped in the string, ie \\ not \). This is then used to build a regex like this:

/[<every character in special, escaped>]/

这篇关于如何检查字符串是否包含 ruby​​ 中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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