使用C语言将下面的字符串中的timestr段和timestamp段给解析出来
时间: 2024-04-30 20:22:35 浏览: 109
timestamp 与日期时间互转的 C 语言实现
5星 · 资源好评率100%
假设字符串为str,可以使用正则表达式来解析出timestr段和timestamp段:
```c
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char* str = "timestr=2022-01-01 12:00:00×tamp=1641015600";
regex_t regex;
int reti;
regmatch_t pmatch[2];
char* timestr;
char* timestamp;
// 编译正则表达式
reti = regcomp(®ex, "timestr=([^&]*)", REG_EXTENDED);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
// 匹配timestr段
reti = regexec(®ex, str, 2, pmatch, 0);
if (!reti && pmatch[1].rm_so != -1) {
int len = pmatch[1].rm_eo - pmatch[1].rm_so;
timestr = (char*)malloc(len + 1);
strncpy(timestr, str + pmatch[1].rm_so, len);
timestr[len] = '\0';
printf("timestr: %s\n", timestr);
} else {
fprintf(stderr, "No match for timestr\n");
}
// 编译正则表达式
reti = regcomp(®ex, "timestamp=([^&]*)", REG_EXTENDED);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
// 匹配timestamp段
reti = regexec(®ex, str, 2, pmatch, 0);
if (!reti && pmatch[1].rm_so != -1) {
int len = pmatch[1].rm_eo - pmatch[1].rm_so;
timestamp = (char*)malloc(len + 1);
strncpy(timestamp, str + pmatch[1].rm_so, len);
timestamp[len] = '\0';
printf("timestamp: %s\n", timestamp);
} else {
fprintf(stderr, "No match for timestamp\n");
}
return 0;
}
```
输出:
```
timestr: 2022-01-01 12:00:00
timestamp: 1641015600
```
阅读全文