dierre
dierre

Reputation: 7220

Using regexp in Java to verify that a string contains a pattern

Simple question. If I need to check if a Regexp contains a simple pattern, in my case it would be ^0039, if I write something like this:

    if(Pattern.matches("^(0039|\\+39)", "00392121")) System.out.println("Yes");
    else System.out.println("No");

I have obviously No as answer because the pattern is missing the 2121. Do I need to transform the pattern in ^(0039|\\+39).* or is there a method more suitable for this?

I'm asking because I'm writing a method for our ETL engine and I'm not sure that everyone who's gonna use this is aware on how regexp works...so I'm foreseeing a lot of email of complaing with an obvious answer: "append .* to your regexp"*

Upvotes: 1

Views: 107

Answers (3)

dacwe
dacwe

Reputation: 43504

I would advise you to use the Matcher.find method:

public static void main(String[] args) {
    Matcher m = Pattern.compile("^(0039|\\+39)").matcher("00392121");

    if (m.find())
        System.out.println("Found");
}

Note: This will only find the first occurrence of the pattern since it starts with ^.


Also note that Pattern.matches(regex, input) boils down to:

Pattern.compile(regex).matcher(input).matches()

Which calls Matcher.matches. And according to the API it matches against the whole input:

The matches method attempts to match the entire input sequence against the pattern.

Upvotes: 2

Oleg Mikheev
Oleg Mikheev

Reputation: 17444

For this particular case I would not use regexp but rather use String's startsWith(String prefix, int toffset) instead.

Especially if you're not sure that everyone who's gonna use this will be aware of how regexp works.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425198

The String.matches() method returns true if the regex matches the whole String.

So yes, you have to add .* to the end.

Upvotes: 1

Related Questions