Java trim 字符和空格

Java trim character and whitespaces

阅读 Java TestNG 测试之上的注释,我的注释为:

@TestInfo(id={ " C26603", " C10047" }) 

其中 TestInfo 只是具有 id() as String array:

的接口
public String[] id() default {};

C26603C10047只是我分配的测试ID。

这是测试结构的样子(例如):

案例 1:

@TestInfo(id={ " C26603", " C10047" })
public void testDoSomething() {
     Assert.assertTrue(false);
}

同样更简洁的情况是:

案例 2:

@TestInfo(id={ "C26603", "C10047" })

可以看到,案例2比案例1更清晰。案例2的test id中没有空格。

如何获取这些 ID 并确保它们的开头没有 C 字符而只是一个纯数字? 例如,我只想 26603 作为我的第一个 ID, 10047 作为第二个 ID。 id 数组中有一些空格(引号内)。我想 trim 所有的东西(比如空格)然后只得到 id。我目前正在应用 for loop 来处理每个 id,一旦我得到纯数字,我想进行第 3 方 API 调用(API 期望纯数字作为输入,因此删除 C因为初始字符和其他空格很重要)。

这是我尝试过的:

TestInfo annotation = method.getAnnotation(TestInfo.class);
if(annotation!=null) {
        for(String test_id: annotation.id()) {
            //check if id is null or empty
            if (test_id !=null && !test_id.isEmpty()) {
         //remove white spaces and check if id = "C1234" or id = "1234"
                    if(Character.isLetter(test_id.trim().charAt(0))) {
                                test_id = test_id.substring(1);
                    }
                    System.out.println(test_id);
                    System.out.println(test_id.trim());
            }
      }
}

以上代码为案例 1 提供了 C26603not 26603。它适用于案例 2。

案例 3:

@TestInfo(id={ " 26603", " 10047" })

对于这种情况,没有 C 作为测试 ID 的起始字符,因此该函数应该足够聪明,只需 trim 个空格并继续。

最简单的方法是使用正则表达式非数字字符 class (\D):

删除非数字的所有内容
test_id = test_id.replaceAll("\D", "");

我强烈建议您调试您的方法。你会学到很多东西。

如果您在此处查看您的 if 声明:

if(Character.isLetter(test_id.trim().charAt(0))) {
    test_id = test_id.substring(1);
}

当您的test_id = " C1234"时,您的条件为真。但是,您的问题变成了 substring.

答案:trim它!

test_id = test_id.trim().substring(1);