I am aware of the trim() function for String and i am trying to implement it in my own to better understand regex. The following code does not seem to work in Java. any input ?
private static String secondWay(String input) {
Pattern pattern = Pattern.compile("^\\s+(.*)(\\s$)+");
Matcher matcher = pattern.matcher(input);
String output = null;
while(matcher.find()) {
output = matcher.group(1);
System.out.println("'"+output+"'");
}
return output;
}
The output for
input = " This is a test " is 'This is a test '
I am able to do it using an alternative way like
private static final String start_spaces = "^(\\s)+";
private static final String end_spaces = "(\\s)+$";
private static String oneWay(String input) {
String output;
input = input.replaceAll(start_spaces,"");
output = input.replaceAll(end_spaces,"");
System.out.println("'"+output+"'");
return output;
}
The output is accurate as
'This is a test'
I want to modify my first method to run correctly and return the result.
Any help is appreciated. Thank you :)