0
public class Main {
    /**
     * @param args
     */
    public static void main(String[] args) {
        String url="http://a.b.com/m/test/index";
        System.out.println(url.replaceAll("^.*?((?<!/)(?:/)(?!/))", ""));
    }
}

The system print is: m/test/index. But in my mind it should print is:/m/test/index. Somebody give some reason?

8
  • Use URI/URL class to process them. Don't play around with regular expression in such case. Commented Sep 16, 2015 at 3:13
  • 1
    While your comment is generally true, a) that's not what the question is about, and b) someone has to write those URL processors. See Asimov's short story "Profession". Commented Sep 16, 2015 at 3:17
  • 1
    Again, I don't disagree. This question is about regex, not specifically URL. The "http" in the string is incidental. Commented Sep 16, 2015 at 3:35
  • 1
    ^.*?((?<!/)(?=/)(?!//)) See Demo Commented Sep 16, 2015 at 3:50
  • 1
    (?:/) will matched the / before m,so we should use (?=/) Commented Sep 16, 2015 at 3:51

1 Answer 1

2

Your regex reads "As few characters as possible up to and including the first slash that is neither preceded nor followed by a slash". The slash itself is clearly included in the regex. The fact that it is in a non-capturing group does not mean that it is not part of the match.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.