[英]Java trim character and whitespaces
在Java TestNG測試之上閱讀注釋,我的注釋為:
@TestInfo(id={ " C26603", " C10047" })
其中TestInfo
只是id() as String array
的接口:
public String[] id() default {};
和C26603
和C10047
只是我指定的測試ID。
以下是測試結構的外觀(例如):
案例1 :
@TestInfo(id={ " C26603", " C10047" })
public void testDoSomething() {
Assert.assertTrue(false);
}
同樣更清潔的情況是:
案例2:
@TestInfo(id={ "C26603", "C10047" })
正如您所看到的,此案例2比案例1更清晰。此案例2在測試ID中沒有空格。
我如何獲取這些ID並確保它們在開始時沒有那個C字符而只是一個純數字? 例如,我只想要第一個id為26603
,第二個為10047
。 id數組中有一些空格(引號內)。 我想修剪一切(如白色空格)並獲得id。 我目前正在申請for loop
來處理每個id,一旦我得到純數字,我想進行第三方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的C26603
而not 26603
它適用於案例2。
案例3:
@TestInfo(id={ " 26603", " 10047" })
對於這種情況,沒有C作為測試ID的起始字符,因此該功能應該足夠智能,只需修剪空白區域並繼續。
最簡單的方法是使用正則表達式非數字字符類( \\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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.