简体   繁体   English

C ++中的正则表达式,用于接受“ \\”

[英]Regex in c++ for accepting “ \”

I am trying to use C++ library to use regex expression . 我正在尝试使用C ++库使用正则表达式。

bool x =   std::regex_match(cInputLayoutRec->InputString, std::regex("^[A-Z0-9-\'// ]*$"));

in this case the result should be true (x) if the input supplied is any of these letters A to Z , 0-9 , \\ , ' AND / 在这种情况下,如果提供的输入是以下字母A到Z,0-9,\\,'AND /

Its working for all the conditions except \\ ie if the input string contains \\ this results into false. 它适用于\\以外的所有条件,即,如果输入字符串包含\\,则结果为false。 I tried with putting /\\ to cater for this special character '\\' even then its not working. 我尝试用/ \\来满足这个特殊字符'\\'的要求,即使它无法正常工作。
Can anyone suggest some inputs if i am missing something ? 如果我错过了什么,谁能提出一些建议?

Thanks in Advance! 提前致谢!

其他答案是正确的,但是由于您使用的是C ++ 11,因此应注意,您也可以使用原始字符串文字,如下所示:

std::regex(R"(^[A-Z0-9-\\'// ]*$)")

You are using \\ in a string, hence it will treated as a string escape sequence (in your case escaping ' . 您在字符串中使用\\ ,因此它将被视为字符串转义序列(在您的情况下,转义'

You need to use \\\\ to have a \\ in a string. 您需要使用\\\\在字符串中包含\\

As the backslash is also an escape character for regexes, you have to escape this again, so use \\\\\\\\ to represent the \\ character in a regex. 由于反斜杠也是正则表达式的转义字符,因此您必须再次将其转义,因此请使用\\\\\\\\表示正则表达式中的\\字符。

The \\ character is used for escaping pretty much everywhere. \\字符几乎可以在任何地方转义 This "everywhere" includes C++ string literals syntax and regex syntax. 此“无处不在”包括C ++字符串文字语法 regex语法。

Your regex definition in C++ should be: 您在C ++中的正则表达式定义应为:

std::regex("^[A-Z0-9-\\\\'// ]*$") 

This is what happens: 这是发生了什么:

  • C++ parser interprets the string literal "^[A-Z0-9-\\\\\\\\'// ]*$" as the string with the following contents: ^[A-Z0-9-\\\\'// ]*$ . C ++解析器将字符串文字 "^[A-Z0-9-\\\\\\\\'// ]*$"为具有以下内容的字符串: ^[A-Z0-9-\\\\'// ]*$ This string is passed to the regex parser. 该字符串传递到正则表达式解析器。 Note that two sequences \\\\ have been "replaced" with \\ . 请注意,两个序列\\\\已被\\替换。

  • Regex parser interprets the \\\\ sequence as literal \\ character in your character class. 正则表达式解析器将\\\\序列解释为字符类中的文字\\字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM