如何比较字符串以匹配c中的特殊格式?
我想检查字符串是否与“PCn.Value”匹配。
IE。它必须匹配 PC1.value, PC2.value,...
sscanf()
有帮助
char S[32];
if (sscanf(str, "PC%[0-9].Valu%1[e]%c", S, &S[30], &S[30])==2)
假设一个数字,这可能既足够又最有效:
if (strncmp (s, "PC", 2)
&& (s[2] >= '0' && s[2] <= '9')
&& strcmp (s+3, ".value"))
{
do_stuff_if_string_matches(s[2]-'0');
}
或者,如果您需要任意无符号整数:
char n[SOME_SIZE];
int count = 0;
if (sscanf (s, "PC%[0-9].value%n", n, &count)
&& count == strlen (s))
{
/* `n' now contains the number as a string. */
do_stuff_if_string_matches(atoi(n));
}
检查字符串是否匹配给定格式的问题是一个相当广泛和棘手的话题。作为一般解决方案,正则表达式是一个有用的工具,解析表达式语法也是如此。但是,在您的情况下,它相当简单,特别是如果n
只达到 9。在这种情况下,这是一个计算效率非常高的解决方案:
#include <string.h>
char check_PC_N_dot_value(char* str) {
// only works when 0 <= n <= 9
return
str[0] == 'P' &&
str[1] == 'C' &&
str[2] >= '0' &&
str[2] <= '9' &&
str[3] == '.' &&
str[4] == 'v' &&
str[5] == 'a' &&
str[6] == 'l' &&
str[7] == 'u' &&
str[8] == 'e' &&
str[9] == 0;
}
使用posix 正则表达式,这样您就可以为进一步、更复杂的测试做好准备。
例如
#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
...
...
regex_t regex;
int reti;
if (regcomp(®ex, "PC[[:digit:]]+\.value", 0))
{
printf("Error compiling regex\n");
return(1);
}
reti = regexec(®ex, yourstring, 0, NULL, 0);
if (reti == 0)
printf("String matches\n");
else
{
if (reti == REG_NOMATCH)
printf("String not matches\n");
else
printf("Error\n");
}
regfree(®ex);