找到重叠子串的多个匹配项

时间:2017-05-01 06:53:58

标签: c++ regex string

我试图找到重叠字符串的多个匹配,带有字边界。一旦找到子字符串,就不会考虑将来的匹配,即下一次搜索将在该子字符串结束后开始。例如,我需要这个字符串匹配:

pattern: "ab ab"
string: "ab ab abxxxab ab ab"
         -----         -----
                    ^ ignore this, since it is not a word boundary
substr found: (0 4)
substr found: (14 18)

我编写了以下代码,但它只找到了第一个子字符串。问题是在拒绝第二场比赛后(由于单词边界),它没有找到第三场比赛,这本来是一个合法的子串。

我得到的输出如下:

string is 0 18<ab ab abxxxab ab ab>
    match found:start=0 end=4
        substr found: (0 4)
string is 5 18<ab ab abxxxab ab ab>
    match found:start=0 end=4
    match found:start=11 end=15

(1)如何修复此正则表达式中的问题,以便第3次匹配也被考虑? (2)我使用显式C代码处理字边界检查,这可以作为正则表达式本身的一部分来完成吗?

#include <iostream>
#include <string>
#include <regex>
using namespace std;
int find_substr(string str, regex pat, int start) {
        int last = str.length() - 1;
    printf("string is %d %d<%s>\n", start, last, str.c_str());
    for(auto it = sregex_iterator(str.begin(), str.end(), pat);
            it != sregex_iterator(); ++it) {
        int idx = it->position();
        int end = idx+ it->length() - 1;
        printf("match found:start=%d end=%d\n", idx, end);
        if(idx<start) {
            continue; //ignore matches before the start index
        }
        if(idx>0) {
            if((str.at(idx-1)>='a' && str.at(idx-1)<='z') ||
                       (str.at(idx-1)>='A' && str.at(idx-1)<='Z')) {
                continue; // not a word boundary, ignore
            }
        }
        if(end<last) {
            if((str.at(end+1)>='a' && str.at(end+1)<='z') ||
                       (str.at(end+1)>='A' && str.at(end+1)<='Z')) {
                continue; // not a word boundary, ignore
            }
        }
        printf("substr found: (%d %d)\n", idx, end);
        return end+1;
    }
    return -1;
}
int main() {
    string str;
    regex pat;
    int next;
    str = "ab ab abxxxab ab ab";
    pat = "ab ab";
    next = find_substr(str, pat, 0);
    if(next>0 && next<str.length()) {
        find_substr(str, pat, next);
    }
}

1 个答案:

答案 0 :(得分:1)

这是你在找什么? WL.fileDialog({ mode: "save" }).then( function(resp){ if(!resp || !resp.data || !resp.data.folders || resp.data.folders.length==0)return; var id=resp.data.folders[0].id; var arr=id.split('.'); if(arr.length==3){ id=arr[arr.length-1]; }else{ id=''; } proc_setfolder(id, resp.data.folders[0].name); }, function(resp){ //alert(resp.error_description); } );

https://regex101.com/r/DtjGrN/1

这可能需要Boost(?),因为我不知道c ++中的标准正则表达式库是否支持\bab ab\b

相关问题