Regular Expression to find string starts with lett

2019-09-16 00:55发布

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.

3条回答
神经病院院长
2楼-- · 2019-09-16 01:45

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.

查看更多
在下西门庆
3楼-- · 2019-09-16 01:48

You could try this.

public List<Product> searchProducts(String keyword) {
            MongoCursor<Product> cursor = collection.find("{name:#}", Pattern.compile(keyword + ".*")).as(Product.class);
            List<Product> products = new ArrayList<Product>();
            while (cursor.hasNext()) {
                Product product = cursor.next();
                products.add(product);
            }
            return products;
        }
查看更多
霸刀☆藐视天下
4楼-- · 2019-09-16 01:51

I have found out the solution and the following worked fine.

db.getCollection('employees').find({employeeName:{$regex: '^Raju.*\\/$'}})
db.getCollection('employees').find({employeeName:{$regex: '\/$'}})
getCollection().find("{employeeName:{$regex: 
              '^Raju.*\\\\/$'}}").as(Employee.class);
getCollection().find("{employeeName:{$regex: '\\/$'}}").as(Employee.class);
getCollection().find("{employeeName:#}", 
               Pattern.compile("\\/$")).as(Employee.class);
getCollection().find("{"Raju": {$regex: #}}", "\\/$").as(Employee.class);

map = new HashMap<>();
map.put("employeeName", Pattern.compile("\\/$"));
coll = getCollection().getDBCollection().find(new BasicDBObject(map));
查看更多
登录 后发表回答