如何在 ruby​​ 中针对正则表达式测试整个字符串? [英] How do I test a WHOLE string against regex in ruby?

查看:18
本文介绍了如何在 ruby​​ 中针对正则表达式测试整个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何针对正则表达式创建字符串,以便在 整个 字符串匹配(不是子字符串)时返回 true?

How do I a string against a regex such that it will return true if the whole string matches (not a substring)?

例如:

test( \ee\ , "street" ) #=> returns false
test( \ee\ , "ee" ) #=> returns true!

谢谢.

推荐答案

您可以将字符串的开头与 \A 匹配,以 \Z 结尾.在 ruby​​ 中,^$ 也分别匹配行的开头和结尾:

You can match the beginning of the string with \A and the end with \Z. In ruby ^ and $ match also the beginning and end of the line, respectively:

>> "a\na" =~ /^a$/
=> 0
>> "a\na" =~ /\Aa\Z/
=> nil
>> "a\na" =~ /\Aa\na\Z/
=> 0

这篇关于如何在 ruby​​ 中针对正则表达式测试整个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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