1

我有以下字符串:

const char *str = "\"This is just some random text\" 130 28194 \"Some other string\" \"String 3\""

我想得到整数28194当然整数会变化,所以我不能这样做strstr("20194")

所以我想知道获取字符串的那部分的好方法是什么?

我正在考虑使用#include <regex.h>它,我已经有一个匹配正则表达式的过程,但不确定 C 中的正则表达式如何使用 POSIX 样式表示法。[:alpha:]+[:digit:]以及性能是否会成为问题。还是使用会更好strchr,strstr

任何想法将不胜感激

4

1 回答 1

0

如果你想使用正则表达式,你可以使用:

const char *str = "\"This is just some random text\" 130 28194 \"Some other string\" \"String 3\"";
regex_t re;
regmatch_t matches[2];
int comp_ret = regcomp(&re, "([[:digit:]]+) \"", REG_EXTENDED);
if(comp_ret)
{
    // Error occured.  See regex.h
}
if(!regexec(&re, str, 2, matches, 0))
{
    long long result = strtoll(str + matches[1].rm_so, NULL, 10);
    printf("%lld\n", result);
}
else
{
    // Didn't match
}
regfree(&re);

你是对的,还有其他方法。

编辑:更改为使用非可选重复并显示更多错误检查。

于 2010-04-10T17:36:21.883 回答