带有黄瓜的正则表达式与给出错误的字符串不匹配,但如果多次编写测试,则会匹配相同的字符串

regular expression with cucumber doesn't match the string giving error but would match the same string if the test is written more than once

我正在 java 中写作,并使用 cucumber 和 eclipse 来搜索具有以下要求的类 IP 字符串

should accept four-digit sequences separated by periods where a digit sequence is defined as follows: Any single digit, Any two-digit characters if the first character is non-zero, A one followed by a zero, one, or two followed by any digit

通过在Stepdefs.java文件中写入合适的正则表达式,我是这样写的

@When("^test_ip_address ((?:(\d)|(1[0-2]\d)|([1-9]\d))\.){3}(?:(\d)|([1-9]\d)|(1[0-2]\d))$")
public void test_ip_address(String arg1) throws Throwable {
    System.out.println("test_ip_address true for: " + arg1);
}

现在,当我在 Test.feature 文件中为此方法编写测试(使用 Gherkin 语言)时,第一个测试总是失败,测试(应该全部通过)

When test_ip_address 1.2.3.4
When test_ip_address 123.34.76.109
When test_ip_address 123.34.76.109
When test_ip_address 105.22.33.44

这不是价值问题,就像当我重新排序这些测试时它总是第一个失败,即使我在另一个测试中使用完全相同的值它通过了!这是我得到的错误

cucumber.runtime.CucumberException: Arity mismatch: Step Definition 'skeleton.Stepdefs.test_ip_address(String) in file:(file path..)' with pattern [^test_ip_address ((?:(\d)|(1[0-2]\d)|([1-9]\d))\.){3}(?:(\d)|([1-9]\d)|(1[0-2]\d))$] is declared with 1 parameters. However, the gherkin step has 7 arguments [3., 3, null, null, 4, null, null]

我搜索了错误,当测试中的参数数量与方法中的参数数量不同时会抛出错误,即使我使用 (?:) 将字符串作为一个参数传递,我不知道这 7 个参数从何而来!也不是错误原因

以下正则表达式应验证所有 IPv4 地址:

String zeroTo255 = "(\d{1,2}|(0|1)\" + "d{2}|2[0-4]\d|25[0-5])"; 

String regex = zeroTo255 + "\."  + zeroTo255 + "\."  + zeroTo255 + "\." + zeroTo255;

改用这个 regex 变量。希望这回答了你的问题:)

cucumber.runtime.CucumberException: Arity mismatch: Step Definition 'skeleton.Stepdefs.test_ip_address(String) in file:(file path..)' with pattern [^test_ip_address ((?:(\d)|(1[0-2]\d)|([1-9]\d))\.){3}(?:(\d)|([1-9]\d)|(1[0-2]\d))$] is declared with 1 parameters. However, the gherkin step has 7 arguments [3., 3, null, null, 4, null, null]

此错误是由于正则表达式有 7 个组。其中捕获 7 个参数。和方法

public void test_ip_address(String arg1) throws Throwable

只声明了 1 个参数 (arg1)。

要仅捕获一个参数,请使用 non capturing group 以避免捕获不必要的组作为方法参数。

表达式应如下所示:

@When("^test_ip_address ((?:(?:(?:\d)|(?:1[0-2]\d)|(?:[1-9]\d))\.){3}(?:(?:\d)|(?:[1-9]\d)|(?:1[0-2]\d)))$")

我们不需要编辑正则表达式,因为它是从我们的特征文件转换为步骤定义文件