模式匹配后如何获取子字符串?并从初始字符串中删除找到的子字符串

How to get substring after pattern match? And remove found subString from Initial String

我有这个字符串

String s1 = "FETCH /Students/Mark/School";

我有这个模式:

String pattern = "FETCH /Students/.+?/School";

匹配后,我需要从该字符串中取出 "Mark"。可能吗?

已解决:getSubString,使用此模式"FETCH /Students/(.+?)/School";

您可以使用一个简单的replaceAll来获得您想要的:

String s1 = "FETCH /Students/Mark/School";
s1 = s1.replaceAll("FETCH /Students/[^/]+/School", "FETCH /Students/School");
System.out.println(s1);

IDEONE demo

[^/]+ 子模式匹配除 / 之外的 1 个或多个字符。由于要保留的部分是已知的,因此不需要使用捕获组,只需在替换字符串中使用文字即可。

这里是获取您寻求的结果的子字符串方式(为了完整性,基于 FETCH /Students/ 是字符串的已知开头的假设,然后跟随一些由 [ 以外的字符组成的子字符串=14=] 到那时 / 加上您需要保留的其余字符串):

String s1 = "FETCH /Students/Mark/School";
String endPart = s1.substring(s1.indexOf("/", 17));
System.out.println(s1.substring(0, 15) + endPart);

another demo