简体   繁体   中英

Java Regex: Remove Everything After Last Instance Of Character

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("");

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.

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.

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()

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(""); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM