Home > Enterprise >  How to remove known text from a String in Java?
How to remove known text from a String in Java?

Time:07-14

I have a String like this:

https://www.thetimes.co.uk/article/record-level-of-poorer-teens-aiming-for-a-degree-m6q6bfbq3

And I know that I want to remove this part:

https://www.thetimes.co.uk/article/

How can I do this? Thanks in advance!

CodePudding user response:

Use String::replace

String oldString = "https://www.thetimes.co.uk/article/record-level-of-poorer-teens-aiming-for-a-degree-m6q6bfbq3";

String newString = oldString.replace ("https://www.thetimes.co.uk/article/", "");

CodePudding user response:

If we phrase the requirement as "remove everything after the last '/'", you can use lastIndexof to find its position and then substring to cut it:

String result = myString.substring(0, myString.lastIndexOf('/')   1);

CodePudding user response:

Another solution using a regexp. It could be useful if you need to deal with the case where the input string doesn't start with the known string.

private static final Pattern RE = Pattern.compile("https://www.thetimes.co.uk/article/(.*)");

...

Matcher matcher = RE.matcher(inputString);
if (matcher.matches()) {
    return matcher.group(1);
} else {
    return inputString; // or null, or whatever
}

CodePudding user response:

We can also use substring

String url=https://www.thetimes.co.uk/article/record-level-of-poorer-teens-aiming-for-a-degree-m6q6bfbq3; url.substring(36,url.length);

  • Related