7

我想扫描像

"[25, 28] => 34"

我写了一个小程序来测试它:

#include <cstdlib>
#include <iostream>

int main() {
        char* line = "[25, 28] => 34";
        char a1[100],  a2[100];
        int i;
        sscanf(line, "[%[^,], %[^\]] => %i", a1, a2, &i);
        std::cout << "a1 = " << a1 <<"\na2 = " << a2 << "\ni = "<<i <<"\n";
        return 0;
}

编译这个给出

warning: unknown escape sequence '\]'

和输出

a1 = 25
a2 = 28
i = -1073746244

如果我将其更改为

sscanf(line, "[%[^,], %[^]] => %i", a1, a2, &i);

我没有收到编译器投诉,但仍然

a1 = 25
a2 = 28
i = -1073746244

我知道问题出在第二个标记上,因为

sscanf(line, "[%[^,], %[0123456789]] => %i", a1, a2, &i);

a1 = 25
a2 = 28
i = 34

但我想对第二个令牌使用终止条件。我怎么做?

4

5 回答 5

12

你要

sscanf(line, "[%[^,], %[^]]] => %i", a1, a2, &i);

注意三个连续的]字符——第一个是你不想在%[集合中匹配的字符,第二个以 the 开头的集合结束,%[第三个匹配]输入中的字符

于 2011-04-21T23:01:51.067 回答
5

正如其他人所提到的......我不确定你想在这里做什么......

假设括号之间的东西总是整数,你可以这样做:

int a, b, c;
sscanf(line, "[%d, %d] => %d", &a,&b,&c);

如果您真的坚持使用正则表达式并希望在括号之间传递一些通用的东西,那么您正在寻找的是:

sscanf(line, "[%[^,], %[^]]] => %d", a1, a2, &i);

第二个正则表达式应该匹配除]末尾之外的所有字符。我相信你试图逃避]以前,但这不是必需的,编译器会抛出一个错误,因为它不知道如何处理这种逃避。

]capture 子句中有 3 个fora2因为第一个是说“不要在字符匹配集中包含这个字符”,第二个是关闭字符匹配集,第三个匹配输入]中的 the [25, 28] => 34

如果我完全误解了你的问题,请澄清一下,我可以修改。

于 2011-04-21T22:54:40.797 回答
3

It look like your question basically boils down to "how to include the ] character into a scanf scanset". It is possible and you don't need to escape it. Specifically for that purpose the language specification states that when the ] character immediately follows the opening [ character or immediately follows the opening ^ character, that ] is considered to be a part of the scanset, not a closing bracket. So, in your case the format specifier is supposed to look as "[%[^,], %[^]]] => %i". No \ necessary.

I see that you almost got it right, except that you forgot the third ] character after the second scanset.

于 2011-04-21T23:10:09.177 回答
0

在我看来,这听起来像是一个编译器(或者实际上是库)错误(尽管您确实需要第三个右括号,而不仅仅是两个)。根据标准(C99,§7.19.6.2):

如果转换说明符以 [] 或 [^] 开头,则右括号字符在扫描列表中,并且下一个右括号字符是结束说明的匹配右括号;

于 2011-04-21T23:00:53.560 回答
-2

你能试一下吗

sscanf(line, "[%s, %s] => %d", a1, a2, &i);
于 2011-04-21T22:43:41.680 回答