最終更新日時(UTC):
が更新

履歴 編集

function
<regex>

std::match_results::position(C++11)

difference_type position(size_type sub = 0) const;

概要

指定されたサブマッチが指す文字列の位置を返す。

要件

ready() == true

戻り値

検索対象文字列の先頭を p とすると、distance(p, (*this)[sub].first)
なお、regex_iterator を逆参照して得られたオブジェクトの場合、基準となる「検索対象文字列の先頭」は各繰り返し毎の検索開始位置ではなくコンストラクタに与えた文字列の先頭である(regex_iterator::operator++の「効果」参照)。

#include <iostream>
#include <regex>

int main()
{
  const char s[] = " abc 0123 defgh ";
  const std::regex re("(\\w+) (\\d+) (\\w+)");

  std::cmatch m;
  if (std::regex_search(s, m, re)) {
    std::cout << "str() = '" << m.str() << "', position() = " << m.position() << std::endl;
    for (std::size_t i = 0, n = m.size(); i < n; ++i) {
      std::cout << "str(" << i << ") = '" << m.str(i) << "', position(" << i << ") = " << m.position(i) << std::endl;
    }
  } else {
    std::cout << "not match" << std::endl;
  }
}

出力

str() = 'abc 0123 defgh', position() = 1
str(0) = 'abc 0123 defgh', position(0) = 1
str(1) = 'abc', position(1) = 1
str(2) = '0123', position(2) = 5
str(3) = 'defgh', position(3) = 10

バージョン

言語

  • C++11

処理系