如何从Java字符串中删除已知的文本?



我有一个这样的字符串:

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

我知道我要删除这部分:

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

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/", "");

如果我们将需求描述为"删除最后一个'/'"之后的所有内容",您可以使用lastIndexof找到它的位置,然后使用substring来剪切它:

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

另一个使用regexp的解决方案。如果您需要处理输入字符串不以已知字符串开头的情况,它可能会很有用。

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
}

我们也可以使用子字符串

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

最新更新