Regular Expression to find string starts with letter and ends with slash /

Kathiresa picture Kathiresa · Aug 24, 2016 · Viewed 16.4k times · Source

I'm having a collection which has 1000 records has a string column.

I'm using Jongo API for querying mongodb.

I need to find the matching records where column string starts with letter "AB" and ends with slash "/"

Need help on the query to query to select the same.

Thanks.

Answer

Geek Josh picture Geek Josh · Aug 24, 2016

I'm going to assume you know how to query using Regular Expressions in Jongo API and are just looking for the necessary regex to do so?

If so, this regex will find any string that begins 'AB' (case sensitive), is followed by any number of other characters and then ends with forward slash ('/'):

^AB.*\/$
^  - matches the start of the string
AB - matches the string 'AB' exactly
.* - matches any character ('.') any number of times ('*')
\/ - matches the literal character '/' (backslash is the escape character)
$  - matches the end of the string

If you're just getting started with regex, I highly recommend the Regex 101 website, it's a fantastic sandbox to test regex in and explains each step of your expression to make debugging much simpler.