मैं सी ++ नियमित अभिव्यक्तियों के लिए नया हूं और उन्हें चार * के बजाय तारों के साथ काम नहीं कर सकता। मैंने जो उदाहरण अब तक देखे हैं वे हमेशा सी स्ट्रिंग के लिए थे।एक सी ++ नियमित अभिव्यक्ति कोड "cmatch" के साथ काम करता है क्यों "smatch" के साथ अपवाद उठाता है?
मेरा असली कार्यक्रम, जिसे मैं यहां दिखाने की कोशिश भी नहीं करता, उप मैचों का उपयोग करता हूं लेकिन मैं उन्हें काम नहीं कर सका, इसलिए मैंने एक बहुत ही सरल कामकाजी उदाहरण को संशोधित करने की कोशिश की लेकिन यह या तो काम नहीं करता है। मैं विजुअल स्टूडियो 2010 अल्टीमेट का उपयोग करता हूं।
मूल - काम कर रहे - कोड:
const char *first = "abcd";
const char *last = first + strlen(first);
std::cmatch mr;
std::regex rx("abc");
std::regex_constants::match_flag_type fl = std::regex_constants::match_default;
std::cout << "search(f, l, \"abc\") == " << std::boolalpha
<< regex_search(first, last, mr, rx) << std::endl;
std::cout << " matched: \"" << mr.str() << "\"" << std::endl;
std::cout << "search(\"xabcd\", \"abc\") == " << std::boolalpha
<< regex_search("xabcd", mr, rx) << std::endl;
std::cout << " matched: \"" << mr.str() << "\"" << std::endl;
संशोधित कोड:
const string first = "abcd"; // char * => string
std::smatch mr; // cmatch => smatch
std::regex rx(string("abc"));
std::regex_constants::match_flag_type fl = std::regex_constants::match_default;
// this works:
std::cout << "search(f, l, \"abc\") == " << std::boolalpha
<< regex_search(first, mr, rx) << std::endl;
std::cout << " matched: \"" << mr.str() << "\"" << std::endl;
// after the next line executes mr seems good to me:
// mr[0] = {3, matched:true, first="abcd", second="d",...}
std::cout << "search(\"xabcd\", \"abc\") == " << std::boolalpha
<< regex_search(string("xabcd"), mr, rx) << std::endl;
// but the following line gives the error
// "Debug assertion failed"
// Expression: string iterators incompatible
std::cout << " matched: \"" << mr.str() << "\"" << std::endl;
अजीब है कि संशोधित कोड का एक हिस्सा काम करता है, जबकि अगले भाग एक अपवाद का कारण बनता है। मैंने श्रीमान [0] .str() का उपयोग करने की भी कोशिश की लेकिन मुझे एक ही त्रुटि संदेश मिला। क्या आप इस समस्या को हल करने में मेरी मदद कर सकते हैं?
धन्यवाद! मैं देखता हूं कि मैंने इसे नहीं सोचा था। यह पूरी तरह से समझाता है कि मेरा मूल कोड क्यों दुर्घटनाग्रस्त हो जाता है। – afalco