测试该字符串以特定子字符串

时间:2017-04-13 09:25:50

标签: ruby-on-rails ruby regex

我正在使用validates_format with检查字符串是否以下列字符开头:

data:image/jpeg;base64

这是我想要测试的典型字符串:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAsICAoIBwsKCQoNDAsNERwSEQ8PESIZGhQcKSQrKigkJyctMkA3LTA9MCcnOEw5PUNFSElIKzZPVU5GVEBHSEX/2wBDAQwNDREPESESEiFFLicuRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUX/wAARCAAKAB4DAREAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAABgUH/8QAIxAAAgEEAQQDAQAAAAAAAAAAAQIDAAQFERMhIjGBBhIyQf/EABYBAQEBAAAAAAAAAAAAAAAAAAQCA//EACARAAICAgEFAQAAAAAAAAAAAAABAhEEIQMSEyIxYdH/2gAMAwEAAhEDEQA/AM4s7JWhdpEil5YyIzz/AFMTAjqR/em+lWkQyjjLQRXHG/1JU62DsGncS0D5XsXY2aHG/IYXkZIxLZyJCza1ye/HSiZqeqE4LW0w1lbVLbJXADhllIlCkdy7359AH3UcEvGjTIjUrDEX6q4kSL+L/a06HoDP2XMuo5sC2hs3DAnXnujoOS31tfP0bjJdtP6G5GaTMXpdixMr7JO991HTqKoS1cnZ/9k=

我的代码是:

validates_format_of :imagebase64,  :with => %r{ \A(data:image/jpeg;base64) }i, :message => "is a invalid data uri base64 file"

它没有用。如何在正则表达式中添加一些东西,以便在字符串有空格时拒绝它?

1 个答案:

答案 0 :(得分:1)

您可以使用

:with => /\Adata:image\/jpeg;base64\S*\z/i

其中\S*匹配零个或多个非空格字符,\z匹配字符串结尾。

请参阅the Rubular demo