[英]How can I use regex in C++ to extract text including spaces between parenthesis
我试图将以下内容提取到 3 个字符串中(text1,所有时间戳,包括空格,不包括括号,text3)。 以下是示例文本和我的代码。
text1(Mon Jan 10 10:10:10 2000):text2
我有以下代码来提取它
regex pattern(".+\\(.+\\):.+");
if( regex_match(message, pattern) ){
auto regex_iterator = std::sregex_iterator(message.begin(), message.end(), pattern);
...
使用std::regex
:
#include <iostream>
#include <regex>
#include <string>
int main( int argc, char ** argv )
{
std::string message = (argc == 2) ? argv[1] : "";
std::smatch match;
if (regex_match( message, match, std::regex("(.*?)\\((.*?)\\):(.*)") ))
{
for (auto m : match)
std::cout << m.str() << "\n";
}
}
使用std::string
方法:
#include <ciso646>
#include <iostream>
#include <string>
int main( int argc, char ** argv )
{
std::string message = (argc == 2) ? argv[1] : "";
auto n1 = message.find( "(" );
auto n2 = message.find( "):" );
if ((n1 != message.npos) and (n2 != message.npos))
{
std::cout
<< message << "\n"
<< message.substr( 0, n1 ) << "\n"
<< message.substr( n1+1, n2-n1-1 ) << "\n" // n1+1 for length of "("
<< message.substr( n2+2 ) << "\n"; // n2+2 for length of "):"
}
}
使用以下内容编译任一示例:
cl /EHsc /W4 /Ox /std:c++17 a.cpp
clang++ -Wall -Wextra -pedantic-errors -O3 -std=c++17 a.cpp
Windows 和 Linux 之间引用单个参数(带空格)的方式不同:
Windows | a.exe "text1(Mon Jan 10 10:10:10 2000):text2" |
Linux | ./a.out 'text1(Mon Jan 10 10:10:10 2000):text2' |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.