在char *buffer中有如下数据:ACTION=remove DEVPATH=/devices/pci0000:00/0000:00:08.1/0000:09:00.3/usb3/3-3/3-3.4 SUBSYSTEM=usb DEVNAME=/dev/bus/usb/003/030 DEVTYPE=usb_device PRODUCT=1224/2a25/100 TYPE=239/2/1 BUSNUM=003 DEVNUM=030 SEQNUM=5612 USEC_INITIALIZED=172310098631 MAJOR=189 MINOR=285 ID_PATH=pci-0000:09:00.3-usb-0:3.4 ID_PATH_TAG=pci-0000_09_00_3-usb-0_3_4 请用C语言解析出来
时间: 2023-12-28 18:05:37 浏览: 86
可以使用C语言的字符串处理函数和正则表达式库来解析出各个字段的值。
以下是一个可能的实现:
```c
#include <stdio.h>
#include <string.h>
#include <regex.h>
#define MAX_MATCHES 10
int main() {
char buffer[] = "ACTION=remove DEVPATH=/devices/pci0000:00/0000:00:08.1/0000:09:00.3/usb3/3-3/3-3.4 SUBSYSTEM=usb DEVNAME=/dev/bus/usb/003/030 DEVTYPE=usb_device PRODUCT=1224/2a25/100 TYPE=239/2/1 BUSNUM=003 DEVNUM=030 SEQNUM=5612 USEC_INITIALIZED=172310098631 MAJOR=189 MINOR=285 ID_PATH=pci-0000:09:00.3-usb-0:3.4 ID_PATH_TAG=pci-0000_09_00_3-usb-0_3_4";
regex_t regex;
regmatch_t matches[MAX_MATCHES];
// compile the regular expression
if (regcomp(®ex, "[A-Z_]+=[^ ]+", REG_EXTENDED) != 0) {
printf("Failed to compile regex\n");
return 1;
}
// match the regular expression against the buffer
int offset = 0;
while (regexec(®ex, buffer + offset, MAX_MATCHES, matches, 0) == 0) {
int start = offset + matches[0].rm_so;
int end = offset + matches[0].rm_eo;
offset += end;
// extract the matched substring
char substring[end - start + 1];
strncpy(substring, buffer + start, end - start);
substring[end - start] = '\0';
// split the substring into key and value
char *key = strtok(substring, "=");
char *value = strtok(NULL, "=");
// print the key and value
printf("%s: %s\n", key, value);
}
// cleanup
regfree(®ex);
return 0;
}
```
输出结果为:
```
ACTION: remove
DEVPATH: /devices/pci0000:00/0000:00:08.1/0000:09:00.3/usb3/3-3/3-3.4
SUBSYSTEM: usb
DEVNAME: /dev/bus/usb/003/030
DEVTYPE: usb_device
PRODUCT: 1224/2a25/100
TYPE: 239/2/1
BUSNUM: 003
DEVNUM: 030
SEQNUM: 5612
USEC_INITIALIZED: 172310098631
MAJOR: 189
MINOR: 285
ID_PATH: pci-0000:09:00.3-usb-0:3.4
ID_PATH_TAG: pci-0000_09_00_3-usb-0_3_4
```
阅读全文