2

重複の可能性:
C++ で数値を文字列に、またはその逆に変換する方法

boost::regex の一致結果を、以下のコードで整数などの他の形式に変換するにはどうすればよいですか?

string s = "abc123";
boost::regex expr("(\\s+)(\\d+)");
boost::smatch match;
if(boost::regex_search(s, match, expr)) {
  string text(match[0]);
  // code to convert match[1] to integer
}
4

1 に答える 1

2

私はあなたが持っていたいと確信しています

string text(match[1]);
// convert match[2] to integer

代わりに、match[0]一致したもの全体 (ここでは abc123) と同様に、サブマッチのインデックスは 1 から始まります。

整数部分への変換に関しては、lexical_castを使用すると便利です。

string s = "abc123";
boost::regex expr("(\\s+)(\\d+)");
boost::smatch match;
if(boost::regex_search(s, match, expr)) {
  string text(match[1]);
  int num = boost::lexical_cast<int>(match[2]);
}
于 2012-10-02T22:57:48.440 に答える