如何在 sscanf() 中使用 RegEx 在 c 中以特定方式标记字符串?

How to use RegEx in sscanf() to tokenize a string a specific way in c?

我想打破字符串中的以下文本:

John, Smith, 10 Maple Street, Cullowhee, NC, 28779, 828.123.4567
   Susan, thompson, 21 Oak Road, Webster, NC, 28711, 828.434.3232
Sarah, foster, 32 Sycamore Street, Sylva, NC, 28712, 828.112.3456
bruce, Hampton, 321 Linden Street, Dillsboro, NC, 28123, 828.432.7895
   Bill, Thompson, 141 Cedar Drive, Sauk City, WI, 43214, 415.323.2254

这是我目前拥有的:

void sort(FILE* in, FILE* out){

char buffer[LINE_LENGTH];
int i = 0;
int j = 0;

while(fgets(buffer, sizeof(buffer), in) != NULL) {
    sscanf(buffer , "%[^,],%[^,],%[^,],%[^,],"
            "%[^,],%[^,],%[^,]", 
            str1, str2, str3, str4, str5, str6, str7);
    i++;
}

无论我做什么,我似乎都无法摆脱 SusanBill 前面的 spaces/tabs 现在。我不确定我需要对 sscanf(buffer , **"%[^,]** 这个第一个正则表达式进行哪些更改才能删除这些空格。我已经尝试在第一个 %[^,] 前面 [^a-zA-Z],尝试用 %[^ ,] , %[^' ',], %[^' \t',] 替换 %[^,]。更改要么什么都不做,要么使所有字符串消失,只有 ,,,,,,,,,,,,,,,,,,,,,,, 出现在控制台上。

*scanf 格式字符串中的白色space 字符指示 *scanf 读取并丢弃任意数量的白色space 字符(如果有的话),直到第一个非白色space 字符。

这个可以在C11标准中看到:

7.21.6.2 The fscanf function

[...]

  1. A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.

因此只需在所有 %[ 之前添加一个 space,这样前导的白色 space 字符就会被剪掉。


注意:最后一个 %[^,] 需要更改为 %[^\n],因为该行后面没有任何逗号。