-6

Here is my code

public class regMatch {

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

Its printing false;

I want to use regular expression in contains method.

How can I use it.

Pratik
  • 1,531
  • 3
  • 25
  • 57

4 Answers4

8

I want to use regular expression in contains method.

How can I use it

you can not use regex in contains method

Community
  • 1
  • 1
vishal_aim
  • 7,636
  • 1
  • 20
  • 23
3

You don't need (and shouldn't use) delimiters in a Java regex

And the contains() method doesn't support regexes. You need a regex object:

Pattern regex = Pattern.compile("[0-9]");
Matcher regexMatcher = regex.matcher(s);
System.out.println(regexMatcher.find());
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

You can use the Pattern class to test for regex matches. However, if you are just testing for the presence of digits in the string, directly testing for this would be more efficient than using a regex.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
1

You can use matches() with the regex .*[0-9].* to find if there is any digit:

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

(or for multiline strings, use the regex (.|\\s)*[0-9](.|\\s)* instead)

An alternative - if you are eager to use contains() is iterate all chars from 0 to 9, and check for each if the string contains it:

    boolean flag = false;
    for (int i = 0; i < 10; i++) 
        flag |= s.contains("" + i);
     System.out.println(flag);
amit
  • 175,853
  • 27
  • 231
  • 333