मुझे बढ़ावा देने के बारे में कुछ सवाल हैं :: regex: मैंने नीचे एक उदाहरण की कोशिश की।
१) ४ वे परमार्थ क्या हैsregex_token_iterator? यह एक "डिफ़ॉल्ट मैच" की तरह लग रहा था, लेकिन आप केवल कुछ नहीं लौटाने के बजाय ऐसा क्यों चाहेंगे? मैंने इसे 4 थे परम के बिना आजमाया, लेकिन यह "संकलन" नहीं था।
2) मुझे आउटपुट मिल रहा है: (1, 0) (0, 0) (३, ०) (0, 0) (५, ०)
क्या कोई समझा सकता है कि क्या गलत हो रहा है?
#include <iostream>
#include <sstream>
#include <vector>
#include <boost/regex.hpp>
// This example extracts X and Y from ( X , Y ), (X,Y), (X, Y), etc.
struct Point
{
int X;
int Y;
Point(int x, int y): X(x), Y(y){}
};
typedef std::vector<Point> Polygon;
int main()
{
Polygon poly;
std::string s = "Polygon: (1.1,2.2), (3, 4), (5,6)";
std::string floatRegEx = "[0-9]*\.?[0-9]*"; // zero or more numerical characters as you want, then an optional ".", then zero or more numerical characters.
// The \. is for . because the first is the c++ escpape character and the second is the regex escape character
//const boost::regex r("(\d+),(\d+)");
const boost::regex r("(\s*" + floatRegEx + "\s*,\s*" + floatRegEx + "\s*)");
// s is white space. We want this to allow (2,3) as well as (2, 3) or ( 2 , 3 ) etc.
const boost::sregex_token_iterator end;
std::vector<int> v; // This type has nothing to do with the type of objects you will be extracting
v.push_back(1);
v.push_back(2);
for (boost::sregex_token_iterator i(s.begin(), s.end(), r, v); i != end;)
{
std::stringstream ssX;
ssX << (*i).str();
float x;
ssX >> x;
++i;
std::stringstream ssY;
ssY << (*i).str();
float y;
ssY >> y;
++i;
poly.push_back(Point(x, y));
}
for(size_t i = 0; i < poly.size(); ++i)
{
std::cout << "(" << poly[i].X << ", " << poly[i].Y << ")" << std::endl;
}
std::cout << std::endl;
return 0;
}
उत्तर:
जवाब के लिए 0 № 1आपका रेगेक्स पूरी तरह से वैकल्पिक है:
"[0-9]*\.?[0-9]*"
खाली स्ट्रिंग से भी मेल खाता है। इसलिए "(\s*" + floatRegEx + "\s*,\s*" + floatRegEx + "\s*)"
एक एकल अल्पविराम से भी मेल खाता है।
आपको कम से कम कुछ अनिवार्य करना चाहिए:
"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)"
यह अनुमति देता है 1
, 1.1
, 1.
या .1
लेकिन नहीं .
:
(?: # Either match...
[0-9]+ # one or more digits, then
(?: # try to match...
. # a dot
[0-9]* # and optional digits
)? # optionally.
| # Or match...
.[0-9]+ # a dot and one or more digits.
) # End of alternation