我正在尝试解决以下问题。
给定字符串和正则表达式模式,给出模式在字符串中出现的次数。 RegEx符号表示如下:
. - 2 occurrences of the previous character,
+ - 4 occurrences of previous character,
* – more than 5 occurrences of the previous character
给出样本输入:
aaaaaannndnnnnnnfffhfhhgjjjwkkkllclc
a.
n+
a*
an.
a.d.
给出样本输出:
5
3
1
1
0
我的方法是将所有RegEx转换为正常模式。即,对于上面的例子,我的RegEx将是:
aa
nnnn
aaaaaa
ann
aadd
然后计算出现次数。但是如果输入RegEx是:
,我无能为力a*d.
请注意,我不能使用任何内置功能,例如 Pattern.Matches 。有什么建议吗?
谢谢。
答案 0 :(得分:1)
以下是解析模式并告诉您输入字符串是否以指定模式开头的方法示例。我没有完成它,因为我认为这是一种家庭作业:
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!
}