ruby regex test for exact match of string

3729 views ruby

I am trying to write a regex to exactly match if a string is a mongo id, not if a string contains a mongo id. My regex for a mongo id is


which works great, but I can't figure out how to write a regex that rejects a URL that contains a mongo id, for example. So, I get this, which is not what I want:

pattern = /[a-z,0-9]{24}/
str1 = "589ab375c3c6416310171b5b"
str2 = ""
str1.match pattern


#<MatchData "589ab375c3c6416310171b5b">

And the second string

str2.match pattern


#<MatchData "589ab375c3c6416310171b5b">

I want the first to match but the second to not.

Thanks for any help, kevin

answered question

1 Answer


You can use ^ and $ to match exactly a whole string. ^ matches the start of a line, and $ matches the end. So:


will match a string containing only the 24 characters of a Mongo ID.

posted this

Have an answer?


Please login first before posting an answer.