我有一个程序返回以下格式的数据:
<CFData 0x1001219c0 [0x7fff7027aee0]>{length = 20, capacity = 20, bytes = 0x8deead13b8ae7057f6a629fdaae5e1200bcb8cf5}
我需要提取8deead13b8ae7057f6a629fdaae5e1200bcb8cf5
(是的,减去0x
)。我尝试使用sscanf
并传递一些正则表达式,但对此一无所知。
知道怎么做吗?非常感谢代码片段。
您可以使用strstr()在输入字符串中定位"字节=0x",并复制除最后一个字符之外的字符串的其余部分:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* s = "<CFData 0x1001219c0 [0x7fff7027aee0]>{length = 20, "
"capacity = 20, "
"bytes = 0x8deead13b8ae7057f6a629fdaae5e1200bcb8cf5}";
char* value = 0;
const char* begin = strstr(s, "bytes = 0x");
if (begin)
{
begin += 10; /* Move past "bytes = 0x" */
value = malloc(strlen(begin)); /* Don't need 1 extra for NULL as not
copy last character from 'begin'. */
if (value)
{
memcpy(value, begin, strlen(begin) - 1);
*(value + strlen(begin) - 1) = 0;
printf("%sn", value);
free(value);
}
}
return 0;
}
您可以使用strtok
来完成此操作。
int main(int argc, char* argv[]) {
char s[] = "<CFData 0x1001219c0 [0x7fff7027aee0]>{length = 20, capacity = 20, bytes = 0x8deead13b8ae7057f6a629fdaae5e1200bcb8cf5}";
const char *tok = "<>[]{}= ,";
char* t = strtok(s, tok);
int take_next = false;
char * res;
while (t) {
if (take_next) {
res = t+2;
break;
}
take_next = !strcmp(t, "bytes");
t = strtok(NULL, tok);
}
printf("%sn", res);
return 0;
}
请注意,这只是一个示例。您应该强烈考虑使用strtok_r
重写它,因为strtok
不是可重入的。