@FubiraiHan

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

[regex] match_result.suffix().firstとsub_match.firstの違いについて

Q&A

Closed

以下のようなコードを書くとエラーが出ます。

#include <iostream>
#include <sstream>
#include <regex>
#include <iterator>

int main(){
	std::string str = "1, 2, 3, 4, 5";
	std::stringstream ss("1, 2, 3, 4, 5");
	std::smatch m;
	std::regex_search(str,m, std::regex("1"));
	std::cout << m.suffix().first;  #ここでエラーがでる
}

エラー内容としては、オペランドと一致する演算子がない、というものです。

一方でcppのリファレンスにあったコードを使うと問題なく出力されます。

#include <iostream>
#include <sstream>
#include <regex>
#include <iterator>

void print(const char* title, const std::ssub_match& sub, const std::string& s)
{
	std::cout << title << ": str() = '" << sub.str() << "', "
		"range = [" << sub.first - std::begin(s) << ", " << sub.second - std::begin(s) << "), "
		"matched = " << std::boolalpha << sub.matched << std::endl;
}

int main(){
	std::string str = "1, 2, 3, 4, 5";
	std::stringstream ss("1, 2, 3, 4, 5");
	std::smatch m;
	std::regex_search(str,m, std::regex("1"));
	print("suffix()", m.suffix(), str);  
}

#出力:
    # suffix(): str() = ', 2, 3, 4, 5', range = [1, 13), matched = true

違いとしてはcoutにsmatch.suffix().firstを入れるか、ssub_match.firstを入れるかなのですが、リファレンスを見ても両者にどういう違いがあるのかわかりませんでした。

なぜ前者はエラーで後者は大丈夫なのでしょうか。

0 likes

1Answer

std::smatch は

match_results<string::const_iterator>

のエイリアス(別名)です
この "string::const_iterator"というのがクラス内のどこで使われているかと言えば
貴方の言っている m.suffix().first の型となります
つまりイテレーターを std::cout に突っ込もうとしたためにコンパイルエラーが発生したわけです
イテレーター単体ではなくちゃんとペアで使ってあげればエラーも出なくなります

std::cout << std::string(m.suffix().first, m.suffix().second);

次にリファレンスでコンパイルエラーが出なかった件ですが
リファレンスのコードをよく見てください

std::cout << "前略 range = [" << sub.first << ", 後略" ;

とは書かれていません

std::cout << "前略 range = [" << sub.first  - std::begin(s) << ", 後略" ;

sub.first - std::begin(s)

つまり イテレーターの引き算でマッチ位置を計算しているだけなのでコンパイルエラーが出ないのです

0Like

Comments

  1. @FubiraiHan

    Questioner

    m.suffix().firstは単なるアドレスみたいな数値が入っていると思っていましたがそういうわけではなかったのですね
    回答ありがとうございました

Your answer might help someone💌