ruby regex test for exact match of string

3704 views ruby
2

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

/[a-z,0-9]{24}/

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 = "http://somewhere.com/589ab375c3c6416310171b5b?review"
str1.match pattern

output:

#<MatchData "589ab375c3c6416310171b5b">

And the second string

str2.match pattern

output:

#<MatchData "589ab375c3c6416310171b5b">

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

Thanks for any help, kevin

answered question

1 Answer

2

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

/^[a-z,0-9]{24}$/

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

posted this

Have an answer?

JD

Please login first before posting an answer.