Reputation: 1188
I have this code in C#:
string data = "something ... 1,000 anything 20,000 other thing...";
string pattern = @"[0-9]+([\,|\.][0-9]{1,})*([\.\,][0-9]{1,})?";
MatchCollection collection = Regex.Matches(data, pattern);
foreach (Match item in collection)
{
Console.WriteLine("{0} - {1} - {2}", item.Value, item.Index, item.Length);
}
Console.WriteLine();
Console.WriteLine("End!");
Console.ReadKey();
... and I tried to convert it in C++ (native code, without .net assemblies), so I get something like this:
void main()
{
string data = "something ... 1,000 anything 20,000 other thing...";
regex pattern("([0-9]+([\\,|\\.][0-9]{1,})*([\\.\\,][0-9]{1,})?)");
const sregex_token_iterator end;
for (sregex_token_iterator i(data.begin(), data.end(), pattern); i != end; ++i)
{
std::cout << i->str() << "-" << i->length() << std::endl;
}
cout << endl << "End!";
fflush(stdin);
getchar();
}
So, how can I get the index of the match?
Upvotes: 0
Views: 1183
Reputation: 1188
I solved this way:
struct MatchInfo
{
string value;
int index;
int length;
};
vector<MatchInfo> DoRegex(string data, string pattern)
{
regex patternRegex(pattern);
sregex_token_iterator end;
vector<MatchInfo> result;
for (sregex_token_iterator i(data.begin(), data.end(), patternRegex); i != end; ++i)
{
MatchInfo item;
item.index = i->first - data.begin();
item.length = i->length();
item.value = i->str();
result.push_back(item);
}
return result;
}
Upvotes: 0
Reputation: 247969
Depending on your compiler, the <regex>
header might be available, in which case you can simply rewrite the regular expression using the C++ API, which should be trivial.
If that's not available, <tr1/regex>
might be available, or failing that, you can use teh Boost.Regex third party lib.
Upvotes: 5