【问题标题】:Regular Expression to find string starts with letter and ends with slash /查找字符串的正则表达式以字母开头并以斜杠/结尾
【发布时间】:2016-08-24 11:56:19
【问题描述】:

我有一个包含 1000 条记录的集合有一个字符串列。

我正在使用 Jongo API 来查询 mongodb。

我需要找到列字符串以字母“AB”开头并以斜杠“/”结尾的匹配记录

在查询上需要帮助以查询以选择相同的。

谢谢。

【问题讨论】:

    标签: regex mongodb jongo


    【解决方案1】:

    我假设您知道如何在 Jongo API 中使用正则表达式进行查询,并且只是在寻找必要的正则表达式来执行此操作?

    如果是这样,此正则表达式将查找以“AB”开头(区分大小写)、后跟任意数量的其他字符并以正斜杠 ('/') 结尾的任何字符串:

    ^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
    

    如果您刚刚开始使用正则表达式,我强烈推荐 Regex 101 网站,它是一个很棒的沙箱,可以在其中测试正则表达式并解释表达式的每个步骤,从而使调试更加简单。

    【讨论】:

    • MongoCursor mongoCursor = getCollection().find(query, Pattern.compile("^Raju.*\\/$")).as(Employee.class);查询是 String query = "{empName:#}";-> 这不起作用
    【解决方案2】:

    我找到了解决方案,以下工作正常。

    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】:

      你可以试试这个。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-20
        • 2013-08-04
        • 1970-01-01
        • 1970-01-01
        • 2021-01-10
        • 2017-07-09
        • 2015-11-07
        • 2017-09-17
        相关资源
        最近更新 更多