0

I want to extract the string from the input string with "/" removed from the beginning and the end (if present).

For example :

Input String : /abcd Output String : abcd

Input String : /abcd/ Output String : abcd

Input String : abcd/ Output String : abcd

Input String : abcd Output String : abcd

Input String : //abcd/ Output String : /abcd

user1522820
  • 1,584
  • 5
  • 18
  • 31
  • 2
    Google is faster than ask question - http://stackoverflow.com/questions/2088037/trim-characters-in-java – SergeyS Jan 10 '13 at 09:26

5 Answers5

5
public static void main(String[] args) {
    String abcd1 = "/abcd/";
    String abcd2 = "/abcd";
    String abcd3 = "abcd/";
    String abcd4 = "abcd";
    System.out.println(abcd1.replaceAll("(^/)?(/$)?", ""));
    System.out.println(abcd2.replaceAll("(^/)?(/$)?", ""));
    System.out.println(abcd3.replaceAll("(^/)?(/$)?", ""));
    System.out.println(abcd4.replaceAll("(^/)?(/$)?", ""));
}

Will work.

Matches the first (^/)? means match 0 or 1 '/' at the beginning of the string, and (/$)? means match 0 or 1 '/' at the end of the string.

Make the regex "(^/*)?(/*$)?" to support matching multiple '/':

String abcd5 = "//abcd///";
System.out.println(abcd1.replaceAll("(^/*)?(/*$)?", ""));
Alex DiCarlo
  • 4,851
  • 18
  • 34
0

Method without regex:

String input  = "/hello world/";

int length = input.length(),
    from   = input.charAt(0) == '/' ? 1 : 0,
    to     = input.charAt(length - 1) == '/' ? length - 1 : length;

String output = input.substring(from, to);
hsz
  • 148,279
  • 62
  • 259
  • 315
0

One more guess: ^\/|\/$ for replace RegEx.

Peter L.
  • 7,276
  • 5
  • 34
  • 53
  • This one: `^\/+|\/+$` will match `/////abcd///////` as well - just in case, but not mentioned in the initial request. – Peter L. Jan 10 '13 at 09:41
  • Why downvote? the initial answer seems to match the initial request))) "with "/" removed **from the beginning and the end (if present)**" – Peter L. Jan 10 '13 at 09:47
-1

You can try

 String original="/abc/";
 original.replaceAll("/","");

Then do call trim to avoid white spaces.

original.trim();
jmventar
  • 687
  • 1
  • 11
  • 32
-2

This one seems works :

/?([a-zA-Z]+)/?

Explanation :

/? : zero or one repetition

([a-zA-Z]+) : capture alphabetic caracter, one or more repetition

/? : zero or one repetition

mdelpeix
  • 177
  • 8