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

1

5 Answers 5

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("(^/*)?(/*$)?", ""));
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

This one: ^\/+|\/+$ will match /////abcd/////// as well - just in case, but not mentioned in the initial request.
Why downvote? the initial answer seems to match the initial request))) "with "/" removed from the beginning and the end (if present)"
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);

Comments

-1

You can try

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

Then do call trim to avoid white spaces.

original.trim();

2 Comments

Only from the start and the end of the string, this would remove all.
Following his examples seems only char '/' at start/end
-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.