这是我要匹配的字符串
str =“hello_my_world”;
regex_t reg;
if (regcomp(®, pattern, REG_EXTENDED | REG_ICASE) != 0) {
exit (-1);
}
if (regexec(®, str, 0, NULL, 0) != 0) {
regfree(®);
/* did not match */
}
regfree(®);
}
如果pattern为hello_*
,则返回true。但如果模式是hello_*_world
,它不会......是预期的吗?
我该如何匹配?
答案 0 :(得分:5)
您需要阅读正则表达式语法。模式hello_*_world
将匹配“hello”,后跟零或更多下划线,然后是下划线,后跟“world”。
你想要一个模式的是hello_.*_world
,其中“hello_”后跟零个或多个任意的chraracters,然后是“_world”。
模式hello_*
匹配,因为您的字符串包含一个“hello”,后跟零个或多个下划线。
答案 1 :(得分:2)
Regex *与glob *不同:它表示“ previous atom”中的0或更多
所以我想你想要:
hello_.*_world
答案 2 :(得分:1)
尝试使用hello_.+_world
或hello_[A-Za-z]+_world
的模式。
*适用于它之前的char(出现0次或更多次),因此它匹配hello_world
,hello__world
,hello___world
等。