Pratik Jaiswal Pratik Jaiswal - 6 months ago 10
Java Question

Java trim character and whitespaces

Reading the annotation on top of Java TestNG test and I have annotation as:

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


where
TestInfo
is just the interface that has
id() as String array
:

public String[] id() default {};


and
C26603
and
C10047
are just test ids that I assign.

Here is how test structure looks like (for example):

CASE 1:

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


Similarly more cleaner case would be:

CASE 2:

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


As you can see this case 2 is more clear than the case 1. This case 2 does not have white spaces in test ids.

How do I fetch these ids and make sure that they don't have that C character in beginning and just a pure number? For example, I just want
26603
for my first id and
10047
for 2nd one. There are some spaces in the id array (inside quotes). I want to trim everything of that (like white spaces) and just get the id. I am currently applying
for loop
to process each id and once I get the pure number, I want to make a 3rd party API call (API expects pure number as input and so removal of C as initial character and other white spaces is important).

Here is what I have tried:

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());
}
}
}


Above code gives me
C26603
and
not 26603
for the case 1. It works for the case 2.

CASE 3:

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


For this case, there is no C as beginning character of test id, so the function should be smart enough to just trim white spaces and go ahead.

Answer

The simplest approach would be to just remove everything that is not a digit, using the regular expression non-digit character class (\D):

test_id = test_id.replaceAll("\\D", "");