gpt4 book ai didi

c - 使用正则表达式检查 .dat 文件

转载 作者:行者123 更新时间:2023-11-30 15:45:47 25 4
gpt4 key购买 nike

我正在使用 fgets 读取文件。我需要根据正则表达式检查文件的每一行。如果存在非字母数字字符,则需要退出程序并显示行号和“坏”字符。发生的事情是它在“坏”角色之前被踢出。这是我的 .dat 文件:

howard jim dave 
joe
(
Maggie

我的程序输出是:

file opened
Digit: howard jim dave
is not alphanumeric on line: 1
Exiting program!
File closed

应该发生的情况是它应该在第 3 行踢出,正如您所看到的,这没有发生。

这是我的正则表达式,位于我的 main.h 文件中:

#ifndef MAIN_H
#define MAIN_H

#ifdef __cplusplus
extern "C" {
#endif

#define BUFF 1024
#define to_find "^[a-zA-Z0-9]+$"

这是我的 fileCheck.c

#include "main.h"

int fileCheck(FILE *fp)
{

int ret_val;
int line_count = 0;
char file[BUFF];
regex_t regex;

if (regcomp(&regex, to_find, REG_EXTENDED) != 0)
{
fprintf(stderr, "Failed to compile regex '%s'\n", to_find);
return EXIT_FAILURE;
}

if (fp != NULL)
{
while (fgets(file, BUFF, fp))
{
line_count++;

if ((ret_val = regexec(&regex, file, 0, NULL, 0)) != 0)
{
printf("Digit: %s is not alphanumeric on line: %d\n", file, line_count);
printf("Exiting program!\n");
return EXIT_FAILURE;
}
}
}

}

我不确定“\n”字符是否有问题。我认为不是。我很清楚 if isalnum() 但我的任务是使用正则表达式。这个问题的可能解决方案是什么?感谢您的建议。

编辑:我想提一下,当我使用 fscanf 而不是 fgets 时,上面的正则表达式工作得很好。更改的原因是我需要计算每一行。如果我是正确的, fscanf 会忽略换行符。我需要某种方法来计算换行符。是否可以使用 fscanf 来计数新的?我的原始文件读取循环是:

while (fscanf(fp, "%11023s", file) != EOF
{
line_count++;
if (regexec(&regex, file, 0, NULL, 0) != 0)
{
printf("%s%d wrong:\n, file, line_count);
return EXIT_FAILURE;
}
}

最佳答案

howard jim dave 包含空格。

编辑3:
我专注于仅查找有效行的匹配的原因是您似乎
使用一个简单的测试场景,稍后将变得更加复杂。
但是,如果这正是您所需要的,那么真正的解决方案就是寻找
非字母数字非空白字符。
如果您使用的正则表达式风格需要从头到尾匹配,
这是行不通的。

  #define to_find "[^a-zA-Z0-9\\s]" 
or,
#define to_find "[^a-zA-Z0-9\\ \\t\\f\\r\\n]"

. . .
Then down here if the regex matches, it found non alpha numeric

if ( regexec(&regex, file, 0, NULL, 0)) == 0 )
{
printf("Digit: %s is not alphanumeric on line: %d\n", file, line_count);
printf("Exiting program!\n");
return EXIT_FAILURE;
}

编辑2:
这是 Posix 引擎吗? regcomp() 返回什么错误代码?您应该将 REG_EXTENDED 设置为 cflag 参数之一。
不幸的是,(?:pattern) 构造是一个扩展规范。

还不如把厨房水槽扔到它上面
REG_EXTENDED | REG_NEWLINE

尝试一下那些flaqs和扑通扑通的声音
"^\\s*[a-zA-Z0-9]+(?:\\s+[a-zA-Z0-9]+)*\\s*$" 直接进入regcomp ()

这可以帮助解决错误代码:

 int res_compile = 0;
if ( (res_compile=regcomp(&regex, to_find, REG_EXTENDED) ) != 0)
{
fprintf(stderr, "Failed to compile regex '%s'\nError code: %d\n", to_find, res_compile);
}

原文:也许你需要

 # ^\s*[a-zA-Z0-9]+(?:\s+[a-zA-Z0-9]+)*\s*$

^
\s*
[a-zA-Z0-9]+
(?: \s+ [a-zA-Z0-9]+ )*
\s*
$

或者

 # \A[^\S\r\n]*[a-zA-Z0-9]+(?:[^\S\r\n]+[a-zA-Z0-9]+)*\s*\z

\A
[^\S\r\n]*
[a-zA-Z0-9]+
(?: [^\S\r\n]+ [a-zA-Z0-9]+ )*
\s*
\z

关于c - 使用正则表达式检查 .dat 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18815237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com