Java program that trims starts and ends public class Program { public static String trimEnd(String value) { // Use replaceFirst to remove trailing spaces. return value.replaceFirst("\s+$", ""); } public static String trimStart(String value) { // Remove leading spaces. return value.replaceFirst("^\s+", ""); } public static void main(String[] args) { String value = " /Test? "; // Use custom trimEnd and trimStart methods. System.out.println("[" + trimEnd(value) + "]"); System.out.println("[" + trimStart(value) + "]"); } }