我使用以下两个正则表达式来匹配数字(例如,1.2、1 ...)
regex_text0 = "[0-9]+|\.[0-9]+|[0-9]+\.[0-9]";
regex_text = "[0-9]+|[.][0-9]+|[0-9]+[.][0-9]+";
以及执行它的以下函数。
static int match_regex (regex_t * r, const char * to_match)
{
const char * p = to_match;
const int n_matches = 10;
regmatch_t m[n_matches];
while (1) {
int i = 0;
int nomatch = regexec (r, p, n_matches, m, 0);
if (nomatch) {
printf ("No more matches.\n");
return nomatch;
}
for (i = 0; i < n_matches; i++) {
int start;
int finish;
if (m[i].rm_so == -1) {
printf("break ");
break;
}
start = m[i].rm_so + (p - to_match);
finish = m[i].rm_eo + (p - to_match);
if (i == 0) {
printf ("$& is ");
}
else {
printf ("$%d is ", i);
}
printf ("'%.*s' (bytes %d:%d)\n", (finish - start),
to_match + start, start, finish);
}
p += m[0].rm_eo;
}
return 0;
}
但是两个正则表达式的结果是不同的。
Trying to find '[0-9]+|[.][0-9]+|[0-9]+[.][0-9]+' in '1.0 + 2.3'
$& is '1.0' (bytes 0:3)
break
$& is '2.3' (bytes 6:9)
break
No more matches.
Trying to find '[0-9]+|.[0-9]+|[0-9]+.[0-9]' in '1.0 + 2.3'
$& is '1.0' (bytes 0:3)
break
$& is ' 2' (bytes 5:7)
break
$& is '.3' (bytes 7:9)
break
No more matches.
问题:
- 这两个正则表达式有什么区别?
- 为什么
regexec()
每次只匹配一个数字,但regexec()
的原型(prototype)却想要一个regmatch_t数组?<
最佳答案
您的第二个正则表达式 [0-9]+|[.][0-9]+|[0-9]+[.][0-9]+
允许像 这样的数字>12.21
和 13.131
,其中第一个仅接受 13.1
或 1.1
,即 之后的一位数字。
如果 .
之前存在数字。这是因为第二个正则表达式末尾有 +
符号。这是两个正则表达式之间的唯一区别。
关于c - 正则表达式:匹配c中的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26843988/