2017-05-01 15 views
0

重複する文字列の複数の一致を単語境界で検索しようとしています。部分文字列が見つかると、それは将来の一致のために考慮されません。つまり、次の検索はその部分文字列の終わりの後に開始されます。たとえば、次の文字列に一致するものが必要です。複数の部分文字列が重複して見つかりました

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) 

私は次のコードを書いていますが、最初の部分文字列しか見つかりません。問題は、2番目の一致(単語の境界による)を拒否した後、3番目の一致が見つかりませんでした。これは正当な部分文字列でした。

私が手出力は次のようになります。

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)、この正規表現で問題を解決する方法? (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

これはあなたが探しているものですか? \bab ab\b

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

これは、ブーストを必要とするかもしれない(?)、\bをサポートC++であれば、標準の正規表現ライブラリ、私にはわからないからです。

+0

いいえ、これは動作しません。同じコードで、pat = "\ bab ab \ b"に変更しました。一致するものは1つも見つかりませんでした。私はブーストなしで解決策を探しています。 – R71

+0

申し訳ありませんが、前のコメントです。できます。私はpatを "\\ bab ab \\ b"に変更しました。それはブーストなしで動作します。 – R71

関連する問題