【问题标题】:Can I use regular expression in contains method [duplicate]我可以在包含方法中使用正则表达式吗[重复]
【发布时间】:2012-12-11 20:01:42
【问题描述】:

这是我的代码

public class regMatch {

    public static void main(String... args)
    {
        String s = "1";
        System.out.println(s.contains("/[0-9]/"));
    }
}

打印错误;

我想在contains 方法中使用正则表达式。

我该如何使用它。

【问题讨论】:

标签: java regex string


【解决方案1】:

您可以使用Pattern 类来测试正则表达式匹配。但是,如果您只是测试字符串中是否存在数字,则直接测试会比使用正则表达式更有效。

【讨论】:

    【解决方案2】:

    我想在 contains 方法中使用正则表达式。

    我该如何使用它

    您可以contains 方法中使用正则表达式

    【讨论】:

      【解决方案3】:

      您不需要(也不应该使用)Java 正则表达式中的分隔符

      contains() 方法不支持正则表达式。你需要一个正则表达式对象:

      Pattern regex = Pattern.compile("[0-9]");
      Matcher regexMatcher = regex.matcher(s);
      System.out.println(regexMatcher.find());
      

      【讨论】:

        【解决方案4】:

        您可以使用matches() 和正则表达式.*[0-9].* 来查找是否有任何数字:

        System.out.println(s.matches(".*[0-9].*"));
        

        (或者对于多行字符串,请改用正则表达式(.|\\s)*[0-9](.|\\s)*

        另一种选择 - 如果您渴望使用 contains(),则迭代从 0 到 9 的所有字符,并检查每个字符串是否包含它:

            boolean flag = false;
            for (int i = 0; i < 10; i++) 
                flag |= s.contains("" + i);
             System.out.println(flag);
        

        【讨论】:

        • 这在多行字符串上失败。
        • @TimPietzcker:感谢您指出这一点。您当然可以将\\s 添加到正则表达式中。见编辑。
        • 哎呀。最好在正则表达式前面加上 (?s)。或者,更好的是,根本不要使用matches(),而是使用我在解决方案中提出的matcher.find()
        • 添加到 Tim Pietzcker 的评论中,(?s) 开启 DOTALL 模式,这使得 . 匹配任何内容。 . 默认不匹配新行。
        猜你喜欢
        • 2010-09-29
        • 1970-01-01
        • 2012-10-11
        • 2020-02-06
        • 2013-05-23
        • 1970-01-01
        • 2011-03-23
        • 2011-02-06
        • 2021-06-20
        相关资源
        最近更新 更多