[英]C++ Regex to match '+' quantifier
I want to match expression of the pattern 我想匹配图案的表达
a space followed by a (addition operator or subtraction operator) 后面跟一个空格(加法运算符或减法运算符)
For example: " +"
should return True
例如:
" +"
应返回True
I have tried the using std::regex_match
on the following regular exp: 我已经尝试在以下常规exp上使用
std::regex_match
:
" [+-]"
, "\\\\s[+-]"
, "\\\\s[+\\\\-]"
, "\\\\s[\\\\+-]"
" [+-]"
, "\\\\s[+-]"
, "\\\\s[+\\\\-]"
, "\\\\s[\\\\+-]"
but they all return false. 但它们都返回假。
What should be the correct expression ? 正确的表达应该是什么?
EDIT 编辑
Here's the test code: 这是测试代码:
#include<iostream>
#include<string>
#include<regex>
using std::cout;
int main()
{
std::string input;
std::cin>>input;
const std::regex ex(" [\\+-]");
std::smatch m;
if( std::regex_match(input,ex))
{
cout<<"\nTrue";
}
else
cout<<"\nFalse";
return 0;
}
Now that you've posted code, we can see what the problem is: 现在您已经发布了代码,我们可以看到问题出在哪里:
std::string input;
std::cin >> input;
The problem is here, operator >>
skips whitespace when it reads, so if you type space plus, cin will skip the space and then your regex will no longer match. 问题出在这里,
operator >>
在读取时会跳过空格,因此,如果键入space plus,cin将跳过该空格,然后您的正则表达式将不再匹配。
To get this program to work, use std::getline
instead to read everything that was input before the user pressed enter (including spaces): 为了使该程序正常工作,请使用
std::getline
来读取用户按下Enter键之前输入的所有内容(包括空格):
std::string input;
std::getline(std::cin, input);
尝试此操作,它将匹配带空格的字符串,后跟一个+或-。
" (\\+|-)"
Usually the minus sign is required to go first: [-abc]
. 通常首先需要减号:
[-abc]
。 This is because not to mix with ranges [ab]
. 这是因为不与范围
[ab]
混合使用。
您可以尝试一下,因为我认为它应该可以工作,但我尚未对其进行测试: " [\\+-]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.