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

梦想的初衷 提交于 2019-12-12 02:08:07

问题


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.


回答1:


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.




回答2:


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));



回答3:


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;
        }


来源:https://stackoverflow.com/questions/39122664/regular-expression-to-find-string-starts-with-letter-and-ends-with-slash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!