C++ c++;11正则表达式:检查字符串中是否存在一组字符

C++ c++;11正则表达式:检查字符串中是否存在一组字符,c++,regex,c++11,C++,Regex,C++11,例如,如果我有字符串:“asdf{asdf}” 我想检查字符串是否包含集合[]{}()中的任何字符 我该怎么做呢 我正在寻找一个通用的解决方案,检查字符串是否在集合中包含字符,以便将来我可以继续在集合中添加查找字符。您的问题不清楚您是否只想检测输入字符串中是否存在搜索集合中的任何字符,或者是否要查找所有匹配项 在这两种情况下,使用std::regex创建正则表达式对象。因为搜索集中的所有字符在正则表达式中都有特殊含义,所以需要对所有字符进行转义 std::regex r{R"([\[\]\{\}

例如,如果我有字符串:“asdf{asdf}”

我想检查字符串是否包含集合
[]{}()
中的任何字符

我该怎么做呢


我正在寻找一个通用的解决方案,检查字符串是否在集合中包含字符,以便将来我可以继续在集合中添加查找字符。

您的问题不清楚您是否只想检测输入字符串中是否存在搜索集合中的任何字符,或者是否要查找所有匹配项

在这两种情况下,使用
std::regex
创建正则表达式对象。因为搜索集中的所有字符在正则表达式中都有特殊含义,所以需要对所有字符进行转义

std::regex r{R"([\[\]\{\}\(\)])"};
char const *str = "asdf{ asdf }";
如果只想检测是否找到了至少一个匹配项,请使用


我知道您在询问regex,但这个特定问题可以不用std::string::find_first_of()解决,它可以找到集合(g)中包含的字符串中第一个字符的位置:


您可以使用
std::distance(first,last)
获得匹配的计数,这些方法在
regex中library@user3791372是的,您可以使用
std::distance
查找匹配数,但是您还应该知道
std::regex_迭代器
是一个前向迭代器,所以距离将具有线性复杂性(尽管对于大多数用例来说这不太可能是一个问题)。@Praetorian我指的是第一种情况,但很好的答案包括了这两种情况。谢谢<代码>标准::字符串::首先查找。
std::cmatch results;

if(std::regex_search(str, results, r)) {
    std::cout << "match found\n";
}
std::cmatch results;

auto first = std::cregex_iterator(str, str + std::strlen(str), r);
auto last = std::cregex_iterator();

if(first != last) std::cout << "match found\n";
while(first != last) {
    std::cout << (*first++).str() << '\n';
}
#include <string>
#include <iostream>

int main()
{
    std::string s = "asdf{ asdf }";
    std::string g = "[]{}()";

    // Does the string contain one of thecharacters?
    if(s.find_first_of(g) != std::string::npos)
        std::cout << s << " contains one of " << g << '\n';

    // find the position of each occurence of the characters in the string
    for(size_t pos = 0; (pos = s.find_first_of(g, pos)) != std::string::npos; ++pos)
        std::cout << s << " contains " << s[pos] << " at " << pos << '\n';
}
asdf{ asdf } contains one of []{}()
asdf{ asdf } contains { at 4
asdf{ asdf } contains } at 11