Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e3e9772

Browse files
committed
Added basic regex parser
1 parent a7a5ac7 commit e3e9772

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.rampatra.strings;
2+
3+
/**
4+
* @author rampatra
5+
* @since 25/11/2018
6+
*/
7+
public class BasicRegexParser {
8+
9+
/**
10+
* Implement a regular expression function isMatch that supports the '.' and '*' symbols.
11+
* The function receives two strings - text and pattern - and should return true if the
12+
* text matches the pattern as a regular expression. For simplicity, assume that the actual
13+
* symbols '.' and '*' do not appear in the text string and are used as special symbols only
14+
* in the pattern string.
15+
*
16+
* @param text
17+
* @param pattern
18+
* @return
19+
*/
20+
private static boolean isMatch(String text, String pattern) {
21+
int textIndex = 0;
22+
int patternIndex = 0;
23+
24+
while (textIndex < text.length()) {
25+
if (patternIndex >= pattern.length()) return false;
26+
27+
if (pattern.charAt(patternIndex) == '.' || text.charAt(textIndex) == pattern.charAt(patternIndex)) {
28+
// if the next character in the pattern is a '*' then forward the text pointer
29+
if (patternIndex < pattern.length() - 1 && pattern.charAt(patternIndex + 1) == '*') {
30+
while (textIndex < text.length() - 1 && text.charAt(textIndex + 1) == text.charAt(textIndex)) {
31+
textIndex++;
32+
}
33+
patternIndex++; // for the '*' in the pattern
34+
}
35+
} else if (patternIndex < pattern.length() - 1 && pattern.charAt(patternIndex + 1) == '*') { // if the text
36+
// and pattern are not equal at the index but the pattern has a '*' after then increment the pattern pointer
37+
textIndex--; // as we incrementing the text pointer outside but we should, in fact, stay at the current text index
38+
patternIndex++;
39+
} else {
40+
return false;
41+
}
42+
textIndex++;
43+
patternIndex++;
44+
}
45+
return true;
46+
}
47+
48+
public static void main(String[] args) {
49+
System.out.println(isMatch("aa", "a")); // output: false
50+
System.out.println(isMatch("aa", "aa")); // output: true
51+
System.out.println(isMatch("abc", "a.c")); // output: true
52+
System.out.println(isMatch("abbb", "ab*")); // output: true
53+
System.out.println(isMatch("acd", "ab*c.")); // output: true
54+
System.out.println(isMatch("abbdbb", "ab*d")); // output: false
55+
System.out.println(isMatch("aba", "a.a")); // output: true
56+
System.out.println(isMatch("acd", "ab*c.")); // output: true
57+
System.out.println(isMatch("abaa", "a.*a*")); // output: true
58+
}
59+
}

0 commit comments

Comments
 (0)