gpt4 book ai didi

python - 正则表达式在 C++ 中不匹配?

转载 作者:行者123 更新时间:2023-11-30 04:43:54 25 4
gpt4 key购买 nike

我的正则表达式有问题。我有一个字符串,该字符串使用正则表达式进行验证,它正在使用 python 脚本,但不能在 c++ 中使用。

工作的 python 代码:

import re
txt = "\x01msvc-server\x1Cmsvc-xyzy4\x02<?xml version=\"1.0\" encoding=\"UTF-8\"?><SVCMessage currency=\"INR\" hostName=\"msvc-xyz4\" language=\"US-en\" retransmit=\"N\" sequence=\"00\" timeout=\"90\" version=\"8\"><Amount>0.01</Amount><BusinessDate>20190506</BusinessDate><CheckNumber>0</CheckNumber><LocalDate>20170506</LocalDate><LocalTime>160722</LocalTime><RequestCode>POINT_REDEMPTION</RequestCode><RevenueCenter>0</RevenueCenter><TerminalID>21</TerminalID><TraceID>190506860722N000000</TraceID><Track2>1161111112</Track2><TransactionEmployee>0</TransactionEmployee></SVCMessage>\x03\x04"
matcher = re.compile(r".*\x01([A-Za-z0-9_-]*)\x1C([A-Za-z0-9_-]*)\x02([^\x00-\x1F\x7F]*)\x03\x04.*")
results = matcher.match(txt)

if results == None:
print ('Invalid query , closed')
else:
print ('sucess')

我的 C++ 代码:

#include <iostream>
#include <regex>
using namespace std;

int main()
{
string a = "\x01msvc-server\x1Cmsvc-xyzy4\x02<?xml version=\"1.0\" encoding=\"UTF-8\"?><SVCMessage currency=\"INR\" hostName=\"msvc-xyz4\" language=\"US-en\" retransmit=\"N\" sequence=\"00\" timeout=\"90\" version=\"8\"><Amount>0.01</Amount><BusinessDate>20190506</BusinessDate><CheckNumber>0</CheckNumber><LocalDate>20170506</LocalDate><LocalTime>160722</LocalTime><RequestCode>POINT_REDEMPTION</RequestCode><RevenueCenter>0</RevenueCenter><TerminalID>21</TerminalID><TraceID>190506860722N000000</TraceID><Track2>1161111112</Track2><TransactionEmployee>0</TransactionEmployee></SVCMessage>\x03\x04";
// Here b is object of regex- Regular Expression
regex b(".*\x01([A-Za-z0-9_-]*)\x1C([A-Za-z0-9_-]*)\x02([^\x00-\x1F\x7F]*)\x03\x04.*");
cout<< a << endl;


if( regex_match(a, b)){
cout << "String is matches Reguler Expreation " << endl;

}else{
cout << "String are not match" << endl;
}

return 0;
}

预期的结果是 - 在 C++ 中字符串匹配 ...

最佳答案

将正则表达式字符串中的 \ 加倍怎么样?

//.........VV...................VV...................VV......VV.........VV......VV...VV
regex b(".*\\x01([A-Za-z0-9-_]*)\\x1C([A-Za-z0-9-_]*)\\x02([^\\x00-\\x1F\\x7F]*)\\x03\\x04.*");

否则你可以使用原始文字字符串

// .....VVV...........................................................................VV
regex b(R"(.*\x01([A-Za-z0-9-_]*)\x1C([A-Za-z0-9-_]*)\x02([^\x00-\x1F\x7F]*)\x03\x04.*)");

题外话未请求的建议:避免使用 using namespace std; 和显式 std using std::cout, std::string std::regex

关于python - 正则表达式在 C++ 中不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57973723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com