user2761431
user2761431

Reputation: 975

Java String Matching the Regex

I am trying to solve the following problem.

Given a string and a Regular Expression pattern, give the number of the times the pattern occurs in the string. RegEx symbols mean as follows:

. - 2 occurrences of the previous character, 
+ - 4 occurrences of previous character, 
* – more than 5 occurrences of the previous character

Sample Input given:

aaaaaannndnnnnnnfffhfhhgjjjwkkkllclc
a.
n+
a*
an.
a.d.

Sample Output given:

5
3
1
1
0

My approach is to convert all the RegEx to normal pattern. i.e., for the above example my RegEx would be:

aa
nnnn
aaaaaa
ann
aadd

and then count the occurrences. But I am clueless what to do if the input RegEx is:

a*d.

Please note that I cannot use any inbuilt functions like Pattern.Matches. Any suggestions?

Thank you.

Upvotes: 1

Views: 422

Answers (1)

Aleksei Shestakov
Aleksei Shestakov

Reputation: 2538

Here is an example of method that would parse your pattern and tell you if the input string starts with specified pattern. I didn't finish it, because i think it is some kind of home work:

boolean startsWithPattern(String pattern, String str) {
    int strPos = 0;
    int patternPos = 0;
    // parse pattern and check input str
    while (patternPos < pattern.length()) {
        char symbol = pattern.charAt(patternPos);
        // TODO this will not work for patterns like `a`, only for `a.`, `b*`, `n+`
        char action = pattern.charAt(patternPos + 1); 
        patternPos += 2;
        switch (action) {
            case '.':
                int end = strPos + 2; // check only two symbols
                for (; strPos < end; ++strPos) {
                    if (str.charAt(strPos) != symbol) {
                        return false; // string don't match
                    }
                }                    
                break;
            case '*':
                // TODO some cycle that would check 5+ positions in str
                break;
            case '+':
                // TODO similar to '.'
                break;
        }
    }
    return true; // string starts with pattern!
}

Upvotes: 1

Related Questions