正则表达式不能像C ++ regex_match那样正常工作 [英] Regex not working as expected with C++ regex_match

查看:466
本文介绍了正则表达式不能像C ++ regex_match那样正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习c ++ 11中的正则表达式,此正则表达式搜索返回false。有人知道我在这里做错了吗? 。我知道。* 代表任何数量的字符,除了换行符。

I'm studying regular expressions in c++11 and this regex search is returning false. Does anybody know what I am doing wrong here? . I know that .* stands for any number of characters except newlines.

所以我期望regex_match返回true,输出为found。
但是输出是未找到。

So i was expecting regex_match() to return true and the output to be "found". However the output is coming out to be "not found".

#include<regex>
#include<iostream>

using namespace std;

int main()
{
    bool found = regex_match("<html>",regex("h.*l"));// works for "<.*>"
    cout<<(found?"found":"not found");
    return 0;
}


推荐答案

您需要使用regex_search而不是regex_match:

You need to use a regex_search rather than regex_match:

bool found = regex_search("<html>",regex("h.*l"));

请参阅 IDEONE demo

简单来说, regex_search 会在 any 在给定字符串中的位置。 regex_match 只会在整个输入字符串匹配时返回true(与匹配在Java中)。

In plain words, regex_search will search for a substring at any position in the given string. regex_match will only return true if the entire input string is matched (same behavior as matches in Java).

regex_match 文档说:


返回目标序列是否与正则表达式 rgx 。$
整个目标序列必须匹配此函数的正则表达式>才能返回true(即,在>匹配之前或之后没有任何其他字符)。对于在匹配只是>序列的一部分时返回true的函数,请参阅 regex_search

regex_search 有所不同:


返回目标序列(主题)中的某些子序列是否与正则表达式 rgx )。

这篇关于正则表达式不能像C ++ regex_match那样正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆