In Set 1, we have discussed general approach for counting the patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0’s.In this post, we will discuss regular expression approach to count the same. Examples:
Input : 1101001
Output : 2
Input : 100001abc101
Output : 2
Below is one of the regular expression for above pattern
10+1
Hence, whenever we found a match, we increase counter for counting the pattern.As last character of a match will always ‘1’, we have to again start searching from that index.
Implementation:
C++
#include <iostream>
#include <regex>
class GFG
{
public:
static int patternCount(std::string str)
{
std::regex regex("10+1");
std::smatch match;
int counter = 0;
while (std::regex_search(str, match, regex))
{
str = match.suffix().str();
counter++;
}
return counter;
}
};
int main()
{
std::string str = "1001ab010abc01001";
std::cout << GFG::patternCount(str) << std::endl;
return 0;
}
|
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG
{
static int patternCount(String str)
{
String regex = "10+1";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
int counter = 0;
while(m.find())
{
m.region(m.end()-1, str.length());
counter++;
}
return counter;
}
public static void main (String[] args)
{
String str = "1001ab010abc01001";
System.out.println(patternCount(str));
}
}
|
Python3
import re
def patternCount(str):
regex = "10+1"
p = re.compile(regex)
counter=0
for m in re.finditer(p,str):
counter+=1
return counter
str = "1001ab010abc01001"
print(patternCount(str))
|
C#
using System;
using System.Text.RegularExpressions;
class GFG
{
static int patternCount(String str)
{
String regex = "10+1";
Regex p = new Regex(regex);
Match m = p.Match(str);
int counter = 0;
while(m.Success)
{
m = m.NextMatch();
counter++;
}
return counter;
}
public static void Main (string[] args)
{
string str = "1001ab010abc01001";
Console.WriteLine(patternCount(str));
}
}
|
Javascript
function patternCount(str) {
const regex = /10+1/g;
let counter = 0;
let match;
while ((match = regex.exec(str)) !== null) {
counter++;
}
return counter;
}
const str = "1001ab010abc01001";
console.log(patternCount(str));
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Related Articles :
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.