【问题标题】:Check if a string contains an element from a list of strings and that substring is at particular location [closed]检查字符串是否包含字符串列表中的元素并且该子字符串位于特定位置[关闭]
【发布时间】:2021-08-27 19:46:29
【问题描述】:

我想检查字符串是否包含列表中的元素,所以我使用了以下代码

names=["larry","stevens","college"]
company="1234_larry_abc(ben)"
company1="23_abc(larry)"
boolean match = names.stream().anyMatch(company::contains); 

两者都适用。但我想检查列表中的字符串是否应该在数字之后,所以只有 company 应该返回 true 而不是 company1。

如何使用正则表达式检查“digits_[String from list]_anything(anything)”

如何为此编码,以便列表中的子字符串如果遵循这个特定的正则表达式则只返回 true,否则返回 false?

不知道为什么这个问题被关闭了。第一个答案真的很有帮助,我正要尝试第二个。我已经给出了我正在尝试的代码并在这里寻求真正的帮助

【问题讨论】:

    标签: java regex


    【解决方案1】:

    您可以使用regex(?<=\d_)\p{Alpha}+,这意味着alphabets preceded by(一个数字后跟一个_)。

    演示:

    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
        public static void main(String[] args) {
            List<String> names = List.of("larry", "stevens", "college");
            String company = "1234_larry_abc(ben)";
            String company1 = "23_abc(larry)";
            System.out.println(names.contains(getMatch(company)));
            System.out.println(names.contains(getMatch(company1)));
        }
    
        static String getMatch(String s) {
            Matcher matcher = Pattern.compile("(?<=\\d_)\\p{Alpha}+").matcher(s);
            String group = "";
            if (matcher.find())
                group = matcher.group();
            return group;
        }
    }
    

    输出:

    true
    false
    

    ONLINE DEMO

    Unmitigated 的一个很好的收获:

    这里不需要stream,因为您使用的是contains

    【讨论】:

      【解决方案2】:

      您可以删除所有前导数字和下划线,然后使用String#startsWith

      boolean match = names.stream().anyMatch(company.replaceAll("^\\d*_", "")::startsWith);
      

      ONLINE DEMO

      【讨论】:

        猜你喜欢
        • 2014-01-29
        • 2010-10-04
        • 1970-01-01
        • 1970-01-01
        • 2012-10-25
        • 2015-07-27
        • 2011-11-09
        • 2013-05-18
        • 1970-01-01
        相关资源
        最近更新 更多