Marius
Marius

Reputation: 499

How to delete everything after second slash

On this topic: How to delete all after last slash? is an answer marked as accepted but that answer do not cover the situation when you have another slash at the end.

I want to delete everything after second slash (/)

Example:

Redirect 410 /component/content/
Redirect 410 /rm/land/8919/
Redirect 410 /a5-Q_/MART_Horizon_Afdj/

to become

Redirect 410 /component/
Redirect 410 /rm/
Redirect 410 /a5-Q_/

Upvotes: 1

Views: 2894

Answers (2)

Przemysław Moskal
Przemysław Moskal

Reputation: 3609

Here is a simple example, how you could achieve deleting the part of String that you ask for with the use of regex. I created a simple array containing source String to make the code look more clear:

String[] strings = { "Redirect 410 /component/content/", "Redirect 410 /rm/land/8919/", "Redirect 410 /a5-Q_/MART_Horizon_Afdj/" };
Pattern p = Pattern.compile("(Redirect 410 /[^/]*/).*"); // Here is the regex I used to get needed part of String
for(int i = 0; i < 3; i++) {
    Matcher m = p.matcher(strings[i]);
    if(m.find()) {
        strings[i] = m.group(1);
        System.out.println(strings[i]);
    }
}

Output you get when using this code:

Redirect 410 /component/
Redirect 410 /rm/
Redirect 410 /a5-Q_/

This is a solution according to Java language as you didn't specify what language you were working with, but I think that solution in other languages could be similar to this one.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Use an expression ^([^/]*/[^/]*/).*$, and replace with $1

enter image description here

([^/]*/[^/]*/) expression captures the part that you want to keep; .*$ captures the rest of the string to the end of line. Replacing with $1 removes the unwanted portion of the string.

Upvotes: 1

Related Questions