Skip to content

Instantly share code, notes, and snippets.

@topin27
Created September 22, 2012 09:16
Show Gist options
  • Save topin27/3765630 to your computer and use it in GitHub Desktop.
Save topin27/3765630 to your computer and use it in GitHub Desktop.
在一个字符串中寻找简单的符合正则表达式的字串,并将其保存到目的数组中,中间用空格间隔。
/*
* 字符串匹配问题,给定一串字符串,按照指定规则对齐进行匹配,并将匹配结果
* 保存至output数组中,多个匹配项用空格间隔,最后一个不需要空格。 要求:
* 1、匹配规则中包含通配符?和*。?表示匹配任意一个字符,*表示匹配任意
* 多个字符串。
* 2、匹配后的输入串不再进行匹配,从当前匹配后的字符串开始重新匹配其
* 它字符串。
*/
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
namespace { // static
/*
* 从kp_src_处开始检验是否匹配kp_regex_,若匹配上,则返回匹配到的字符数,
* 否则返回0.
*/
int check_match(const char *kp_src_, const char *kp_regex_)
{
if (kp_src_ == NULL || kp_regex_ == NULL)
return 0;
bool star = false;
int i = 0, j = 0;
while (kp_regex_[j] != '\0') {
if (kp_regex_[j] == '?') {
i++;
j++;
}
else if (kp_regex_[j] == '*') {
star = true;
j++;
}
else { // char.
if (star == false) {
if (kp_src_[i] != kp_regex_[j])
break;
else {
i++;
j++;
}
}
else {
if (kp_src_[i] != kp_regex_[j])
i++;
else {
i++;
j++;
star = false;
}
}
}
}
if (kp_regex_[j] == '\0' && star == false)
return i;
else if (kp_regex_[j] == '\0' && star == true) // the regex string is end by "*"
return strlen(kp_src_);
else
return 0;
}
/*
* 若匹配到,则返回匹配到的字符串首地址,并将匹配到的个数放入参数n_中。
* 若没有匹配到,则返回NULL。
*/
const char* find_first_match(const char *kp_src_, const char *kp_regex_, int &n_)
{
if (kp_src_ == NULL || kp_regex_ == NULL)
return NULL;
const char *kp_tmp = kp_src_;
int n = 0;
while (*kp_tmp) {
if ((n = check_match(kp_tmp, kp_regex_)) != 0) {
n_ = n;
return kp_tmp;
}
kp_tmp++;
}
n_ = 0;
return NULL;
}
} // end of namespace.
/*
* 将kp_src_中的所有符合正则表达式kp_regex_的字符串保存在p_out指向的数组中,
* 中间用空格间隔。
*/
void get_all_match_string(const char *kp_src_, const char *kp_regex_, char *p_out_)
{
const char *kp_tmp = kp_src_;
char *p_outpos = p_out_;
int n = 0;
while ((kp_tmp = find_first_match(kp_tmp, kp_regex_, n)) != NULL) {
strncpy(p_outpos, kp_tmp, n);
p_outpos += n;
strncpy(p_outpos, " ", 1);
p_outpos++;
kp_tmp += n;
}
}
int main()
{
string insrc, regex;
cout << "input src:";
cin >> insrc;
cout << "input regex sting:";
cin >> regex;
char out[100];
memset(out , 0, sizeof(out));
get_all_match_string(insrc.c_str(), regex.c_str(), out);
cout << out << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment