This discussion is archived
10 Replies Latest reply: Nov 19, 2012 3:40 AM by AjayL RSS

Using Regex Query to replace spaces.

AjayL Newbie
Currently Being Moderated
Hello

I am new to Regex and amd trying to replace the space characters before and after the string without any trailing and leading spaces:

For example :
String word = "   Java  Regex      "; 

Output Required: Java Regex
I am writing the following code but it is not removing the spaces :
public String test(){

     String regex = "(^)(\\s+) $";
     Pattern spacePattern = Pattern.compile(regex);
     Matcher spaceMatcher = spacePattern.matcher(criteria);

     String resultCriteria = "";

     if (spaceMatcher.find()) {
          resultCriteria = spaceMatcher.replaceAll(" ");
     }

     return resultCriteria.toLowerCase();
}


Assert.assertEquals("java Regex", searchNormalizer.normalize("   JaVa        REGex   "));   // Fail
Ouput :  (space)JaVa        REGex(space)
Can someone please advise the right way?

Thanks

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points