Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit a4593b1

Browse filesBrowse files
added 10. Regular Expression Matching.js
1 parent 309eef0 commit a4593b1
Copy full SHA for a4593b1

File tree

Expand file treeCollapse file tree

1 file changed

+39
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+39
-0
lines changed
+39Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
function isMatch(str, pat) {
2+
return recursiveIsMatch(0, 0, str, pat);
3+
}
4+
function recursiveIsMatch(i, j, str, pat) {
5+
const inputStringLength = str.length;
6+
const patternLength = pat.length;
7+
8+
// Reached the end of the pattern
9+
if (j == patternLength) {
10+
// Return whether or not we've also reached the end of the string (entire string has passed)
11+
return i == inputStringLength;
12+
}
13+
14+
// If the current pattern character is followed by a * (is a wildcard)
15+
if (j + 1 < patternLength && pat.charAt(j + 1) == '*') {
16+
// Assume 0 matches of the current pattern character, move on to the next point in the pattern (after the asterisk)
17+
if (recursiveIsMatch(i, j + 2, str, pat)) return true;
18+
19+
// Loop through the remaining characters, so long as they match by character (or .)
20+
while (
21+
i < inputStringLength &&
22+
(pat.charAt(j) == '.' || str.charAt(i) == pat.charAt(j))
23+
) {
24+
// Check the rest of the string (1 character forward), against the next point in the pattern (after the asterisk)
25+
if (recursiveIsMatch(++i, j + 2, str, pat)) return true;
26+
}
27+
}
28+
// If the current pattern character is not a wildcard, and matches the current string character
29+
else if (
30+
i < inputStringLength &&
31+
(pat.charAt(j) == '.' || str.charAt(i) == pat.charAt(j))
32+
) {
33+
// Move onto the next character, and the next character of the pattern
34+
return recursiveIsMatch(i + 1, j + 1, str, pat);
35+
}
36+
37+
// String does not match current point in pattern
38+
return false;
39+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.