1

I'm adding a validation check on a rails model using the following regex:

validates :reference, :presence => true, :format => { :with => /^[a-zA-Z0-9_. ]*$/i }

This check will match any non alphanumeric chars and ignores underscore and dot.

When testing on rubular.com, the regex fails to match any of the above mentioned patterns. Instead, rubular matches using this regexp:

/[^a-zA-Z0-9_. ]/i

Anyone knows what the reason behind the difference between the two?

Thanks

1 Answer 1

2

^ has two meanings. When used outside of brackets, it means "line begins with". When used inside brackets, it means that what is matched is the opposite. I feel like I'm not clear so : [a-z] would match every lower case letter, while [^a-z] would match anything but a lower case letter.

Sign up to request clarification or add additional context in comments.

4 Comments

You could also say that [^...] negates the character class [...]. I don't know if that's any clearer though.
I'm not entirely sure that this is the case. Head over to rubular.com and try both: the one with [^...] does match non alpha chars, while the one with ^[..] isn't doing the reverse.
as @muistooshort said, [^...] negates the character class [...]. ^[...] is not supposed to be the opposite of [^...]. This is one case of ambiguity in regexp syntax, but you'll get used to it. The cheat sheet at the bottom of rubular should help you keep things clear
@cnicolaou: /^[a-z]/ matches anything that begins with 'a' through 'z', /[^a-z]/ matches anything that doesn't contain 'a' through 'z'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.