正则表达式 C 无法按预期使用通配符 * 和插入符号工作



我已经使用REGEX库编写了REGEX代码。但是我面临的通配符 *和Caret的问题很少。

以下是我的正则代码:

status = regcomp (&r, tmp, REG_EXTENDED);
if(!status) {
    if(regexec(&r, string_to_compare, 0, NULL, 0) == 0) {
        /* Do something */
    }
}

其中TMP是字符串模式,String_to_compare只是一个字符串,必须与Regex r。

匹配

案例1: *无法正常工作。

a。带有模式" N1*"

在String_to_compare中传递字符串之后:

to-dallas
newyork-to-dallas1
n1

REGEXEC返回所有上述字符串的0,而string n1则返回0。

工作案例:

带有" newyork to-dallas*"

与上述相同的字符串,

Regexec仅返回0,仅用于" Newyork-to-Dallas1"。

案例2:脑线无法正常工作。

使用模式"^to-da*"和与上述相同的字符串,Regexec并不为所有字符串返回0。

如果我缺少一些东西,请告诉我。预先感谢。

在简而言之, *是正则表达式中的量词,表示 0或更多出现。用.*代替它应产生预期的结果。

请注意,n1*还与输入字符串中的任何n匹配,因为这意味着n和可选的1(0或更多出现)。n1.*已经需要在字符串中存在n1才能返回匹配。

run("n1.*", "to-dallas");          // => No match
run("n1.*", "newyork-to-dallas1"); // => No match
run("n1.*", "n1");                 // => Match "n1"

对于newyork-to-dallas*(和newyork-to-dallas.*),它将与newyork-to-dallas1匹配:

run("newyork-to-dallas*","newyork-to-dallas1"); // => Matches "newyork-to-dallas"
run("newyork-to-dallas.*","newyork-to-dallas1"); // => Matches "newyork-to-dallas1" as .* matches "1"

至于Caret,它在字符串的开头匹配。

// Caret
run("^to-da.*", "to-dallas");          => Matches "to-dallas"
run("^to-da.*", "newyork-to-dallas1"); => No match (not at the beginning)
run("^to-da.*", "n1");                 => No match

请参阅编码地上的完整演示程序

最新更新