簡體   English   中英

C中的Posix Regex錯誤

[英]Posix Regex error in C

我在C中使用posix正則表達式遇到麻煩。我只想檢查字符串是否為字母數字(非常簡單),但是每當嘗試添加錨點時都會遇到麻煩。 正則表達式為char pattern[20] = "^[a-zA-Z0-9]+$"; 但是當我嘗試將其與char* str = "9abc1";匹配時char* str = "9abc1"; 我的程序告訴我這不是比賽。 我也嘗試過^[[:alnum:]]+$的類似問題。 我一直在修改我的正則表達式的語法,但是當我可以使它匹配時,再加上連字符也會給我帶來不正確的結果(不應該匹配的地方,特別是如果連字符位於末尾)。 顯然,我在犯一些基本的語法錯誤,但是似乎無法弄清楚。 有什么建議嗎?

您要設置REG_EXTENDED嗎? 這對我來說很好:

#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>
#include <regex.h>

int main(void) {
    regex_t rtype;

    int i = regcomp(&rtype, "^[a-zA-Z0-9]+$", REG_NOSUB | REG_EXTENDED);
    if ( i == 0 ) {
        printf("Regex compiled successfully.\n");
    } else {
        printf("Regex did not successfully compile.\n");
        return EXIT_FAILURE;
    }

    i = regexec(&rtype, "9abc1", 0, NULL, 0);
    if ( i == 0 ) {
        printf("Matched regex.\n");
    } else {
        char buffer[1000];
        regerror(i, &rtype, buffer, sizeof(buffer));
        printf("Regex error: %s\n", buffer);
    }

    return EXIT_SUCCESS;
}

和產量:

paul@local:~/src/c/scratch/$ ./regextest
Regex compiled successfully.
Matched regex.

POSIX基本正則表達式語法中不存在+量詞,這可能會讓您失望。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM