3

Say I have a string:

/first/second/third

And I want to remove everything after the last instance of / so I would end up with:

/first/second

What regular expression would I use? I've tried:

String path = "/first/second/third";
String pattern = "$(.*?)/";
Pattern r = Pattern.compile(pattern2);
Matcher m = r.matcher(path);
if(m.find()) path = m.replaceAll("");

4 Answers 4

10

Why use a regex at all here? Look for the last / character with lastIndexOf. If it's found, then use substring to extract everything before it.

Sign up to request clarification or add additional context in comments.

2 Comments

+1, though, I think the OP wants to extract everything before it.
@damo You're right; I've updated my answer (and substring link).
5

Do you mean like this

s = s.replaceAll("/[^/]*$", "");

Or better if you are using paths

File f = new File(s);
File dir = f.getParent(); // works for \ as well.

2 Comments

You mean replaceAll I think.
@arshajii Yes, replace() doesn't do regex.
1

If you have a string that contains your character (whether a supplemental code-point or not), then you can use Pattern.quote and match the inverse charset up to the end thus:

String myCharEscaped = Pattern.quote(myCharacter);
Pattern pattern = Pattern.compile("[^" + myCharEscaped + "]*\\z");

should do it, but really you can just use lastIndexOf as in

myString.substring(0, s.lastIndexOf(myCharacter) + 1)

To get a code-point as a string just do

new StringBuilder().appendCodePoint(myCodePoint).toString()

Comments

0

Despite the answers avoiding regex Pattern and Matcher, it's useful for performance (compiled patterns) and it'still pretty straightforward and worth mastering. :)

Not sure why you have "$" up front. Try either:

  1. Matching starting group

    String path = "/first/second/third";
    String pattern = "^(.*)/";  // * = "greedy": maximum string from start to last "/"
    Pattern r = Pattern.compile(pattern2);
    Matcher m = r.matcher(path);
    if (m.find()) path = m.group();
    
  2. Stripping tail match:

    String path = "/first/second/third";
    String pattern = "/(.*?)$)/"; // *? = "reluctant": minimum string from last "/" to end
    Pattern r = Pattern.compile(pattern2);
    Matcher m = r.matcher(path);
    if (m.find()) path = m.replace("");
    

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.