ahmad lolah
ahmad lolah

Reputation: 15

how to find the number of a specific pattern appeared in an other pattern using regular expression?

I'm trying to solve a problem using regular expression where I need to find the replicated pattern in another one but i have a problem in the interleaved pattern for example: 1010 and 10101010

the answer must be 3 but it gives me 2

int count=0;
Pattern expression = Pattern.compile(s);

Matcher matcher = expression.matcher(scanner.next());
while(matcher.find())
{count++;}
System.out.println(count);

Upvotes: 1

Views: 60

Answers (1)

Josh W.
Josh W.

Reputation: 102

Once the variable is found in the first one it searches from there and on, so it gett's complicated to actually find all matches in your way.

Here is a recursive solution I've modified from old home work project, probably not optimised but it works.

public static void main(String[] args) 
    {  
         String str1 = "1010";
         String str2 = "10101010";
         int len = str2.length();
         System.out.println(match(str1,str2,len,len,0));
    } 
    static int match(String str1,String str2,int len,int j,int times)
    {
        if(j == 0)
            return  times;
        Pattern p = Pattern.compile(str1);
        Matcher m = p.matcher(str2);
        int n = 0;
        if(m.find()){
             n = m.start()+1;
             times++;
        }
        return match(str1,str2.substring(n,str2.length()),str2.length(),--j,times);
    }

Upvotes: 1

Related Questions