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
For your example data your could use anchors \\A
and \\z
. The data does not contain a comma so you can omit that from the character class .
For example:
pattern = /\\A[a-f0-9]{24}\\z/
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.