gpt4 book ai didi

c - 如何使用 regex.h 查找美元符号

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:57 25 4
gpt4 key购买 nike

下面是我的代码,我想在其中查找字符串是否包含 $ 符号,但它显示错误:error: unknown escape sequence '\$'

#include <sys/types.h>
#include <regex.h>
#include <stdio.h>

#define MAX_MATCHES 1 //The maximum number of matches allowed in a single string

void match(regex_t *pexp, char *sz) {
regmatch_t matches[MAX_MATCHES]; //A list of the matches in the string (a list of 1)
//Compare the string to the expression
//regexec() returns 0 on match, otherwise REG_NOMATCH
if (regexec(pexp, sz, MAX_MATCHES, matches, 0) == 0) {
printf(" matches characters ");
} else {
printf(" does not match\n");
}
}

int main() {
int rv;
regex_t exp; //Our compiled expression
//1. Compile our expression.
//Our regex is "-?[0-9]+(\\.[0-9]+)?". I will explain this later.
//REG_EXTENDED is so that we can use Extended regular expressions
rv = regcomp(&exp, "\$", REG_EXTENDED);
if (rv != 0) {
printf("regcomp failed with %d\n", rv);
}
//2. Now run some tests on it
match(&exp, "Price of iphone is $800 ");

//3. Free it
regfree(&exp);
return 0;
}

最佳答案

您需要转义反斜杠:

rv = regcomp(&exp, "\\$", REG_EXTENDED); 

关于c - 如何使用 regex.h 查找美元符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12366446/

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