C 中的解析/匹配字符串出现

发布于 2024-08-28 01:11:34 字数 470 浏览 5 评论 0原文

我有以下字符串:

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

我想获取整数28194,当然整数会有所不同,所以我不能这样做strstr("20194")

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

我正在考虑使用 #include 我已经有一个匹配 regexp 的过程,但不确定 C 中的 regexp 使用 POSIX 风格表示法会是什么样子。 [:alpha:]+[:digit:] 以及性能是否会成为问题。或者使用 strchr,strstr 会更好吗?

任何想法都会很感激

I have the following string:

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

I would like to get the the integer 28194 of course the integer varies, so I can't do strstr("20194").

So I was wondering what would be a good way to get that part of the string?

I was thinking to use #include <regex.h> which I already have a procedure to match regexp's but not sure how the regexp in C will look like using the POSIX style notation. [:alpha:]+[:digit:] and if performance will be an issue. Or will it be better using strchr,strstr?

Any ideas will be appreciate it

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感情旳空白 2024-09-04 01:11:34

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

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);

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

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

If you want to use regex, you can use:

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);

You're correct that there are other approaches.

EDIT: Changed to use non-optional repetition and show more error checking.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文