【问题标题】:Replacing a char in string with any letter用任何字母替换字符串中的字符
【发布时间】:2017-09-08 14:38:13
【问题描述】:

我正在寻找一种将通配符添加到字符串的方法,这样我就可以从近似匹配中搜索,所以如果我在字符串列表中搜索单词“b*ke”(其中 * 是通配符) , 我会得到 {bake, bike, byke, boke} 回来,这在 java 中可能吗?

【问题讨论】:

    标签: java regex wildcard


    【解决方案1】:

    你已经找到了你需要的“正则表达式”。

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    final String regex = "b[a-z]{1}ke";
    final String string = "bake, bike, byke, boke";
    
    final Pattern pattern = Pattern.compile(regex);
    final Matcher matcher = pattern.matcher(string);
    
    while (matcher.find()) {
        System.out.println("Full match: " + matcher.group(0));
        for (int i = 1; i <= matcher.groupCount(); i++) {
            System.out.println("Group " + i + ": " + matcher.group(i));
        }
    }
    

    【讨论】:

    • 我会建议使用 b.ke 作为正则表达式,这似乎更接近 OP 想要的。或者b[a-z]ke.
    • 此外,您没有在正则表达式中对任何内容进行分组,因此显示与其组索引关联的每个组似乎毫无意义。也许您想计算匹配数?
    【解决方案2】:

    一切都是真的

        System.out.println("bike".matches("b.ke"));
        System.out.println("bake".matches("b.ke"));
        System.out.println("b1ke".matches("b.ke"));
    
        System.out.println("b123ke".matches("b.+ke"));
        System.out.println("b[wait_for_it]ke".matches("b.+ke"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-31
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 2020-11-21
      • 2016-10-26
      • 1970-01-01
      相关资源
      最近更新 更多