簡體   English   中英

使用具有特殊字符的正則表達式標記化c ++字符串

[英]tokenize a c++ string with regex having special characters

我試圖找到一個字符串中的標記,其中包含單詞,數字和特殊字符。 我嘗試了以下代碼:

#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
    string str("The ,quick brown. fox \"99\" named quick_joe!");
    regex reg("[\\s,.!\"]+");
    sregex_token_iterator iter(str.begin(), str.end(), reg, -1), end;
    vector<string> vec(iter, end);
    for (auto a : vec) {
        cout << a << ":";
    }
    cout    << endl;
}

得到以下輸出:

The:quick:brown:fox:99:named:quick_joe:

但我想要輸出:

The:,:quick:brown:.:fox:":99:":named:quick_joe:!:

我應該使用什么正則表達式? 如果可能的話,我想堅持使用標准的c ++,即我不喜歡使用boost的解決方案。

(有關此問題的java版本,請參閱43594465 ,但現在我正在尋找一個c ++解決方案。基本上,問題是如何將Java的Matcher和Pattern映射到C ++。)

您要求將不匹配的子串(子匹配-1)與整個匹配的子串(子匹配0)交錯,這略有不同:

sregex_token_iterator iter(str.begin(), str.end(), reg, {-1,0}), end;

這會產生:

The: ,:quick: :brown:. :fox: ":99:" :named: :quick_joe:!:

由於您只想刪除空格,因此請更改正則表達式以消耗周圍的空白,並為非空白字符添加捕獲組。 然后,只需在迭代器中指定子匹配1,而不是子匹配0:

regex reg("\\s*([,.!\"]+)\\s*");
sregex_token_iterator iter(str.begin(), str.end(), reg, {-1,1}), end;

產量:

The:,:quick brown:.:fox:":99:":named quick_joe:!:

拆分相鄰單詞之間的空格也需要拆分“只是空格”:

regex reg("\\s*\\s|([,.!\"]+)\\s*");

但是,您最終會得到空的子匹配:

The:::,:quick::brown:.:fox:::":99:":named::quick_joe:!:

容易丟棄那些:

regex reg("\\s*\\s|([,.!\"]+)\\s*");
sregex_token_iterator iter(str.begin(), str.end(), reg, {-1,1}), end;
vector<string> vec;
copy_if(iter, end, back_inserter(vec), [](const string& x) { return x.size(); });

最后:

The:,:quick:brown:.:fox:":99:":named:quick_joe:!:

如果您想使用Java相關問題中使用的方法,也可以在這里使用匹配方法。

regex reg(R"(\d+|[^\W\d]+|[^\w\s])");
sregex_token_iterator iter(str.begin(), str.end(), reg), end;
vector<string> vec(iter, end);

請參閱C ++演示 結果:: The:,:quick:brown:.:fox:":99:":named:quick_joe:!: 請注意,這與Unicode字母不匹配,因為\\w\\d\\s )在std::regex不能識別Unicode。

圖案細節

  • \\d+ - 1位或更多位數
  • | - 要么
  • [^\\W\\d]+ - 1個或多個ASCII字母或_
  • | - 要么
  • [^\\w\\s] - 除了ASCII字母/數字, _和空格之外的1個字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM