我需要在斜杠“ /”之后获取某个字符串值,但是由于字符串的格式值并不总是相同,因此我遇到了麻烦。
字符串的值是ff:
String raw = "Announcements/announcement_id)";
我这里需要的只是 announcement_id ,可以使用lastIndexOf("/")+1
获得,但这并不总是字符串的格式,它也可能像这样。
String raw = "Announcements/announcement_id/Comments/comment_id)";
这里我需要的都是 announcement_id 和 comment_id 。
最后一部分的字符串值也可能是这样。
String raw = "Announcements/announcement_id/Comments/comment_id/Replies/reply_id)";
这里我需要的都是 comment_id 和 reply_id 。
如何正确使用if else语句?
if(has only one slash)
use lastIndexOf("/")+1 to get the id
else if (has three or more slashes)
get the value after second to the last forward slash and last forward slash
答案 0 :(得分:4)
您可以使用此正则表达式,该正则表达式允许字符串中的可选部分并适当地捕获announcement_id
,comment_id
和reply_id
(?:Announcements/([^/]*))(?:/Comments/([^/]*))?(?:/Replies/([^/]*))?\)
分别可以通过组1,组2或组3进行访问。
由于每个部分都是可选的,因此它允许您有选择地具有reply_id而无需commend_id,并且根据您的示例,我已将announcement_id强制设置为强制性,甚至您可以将其设置为可选。
查看此示例Java代码,
List<String> list = Arrays.asList("Announcements/announcement_id)",
"Announcements/announcement_id/Comments/commend_id)",
"Announcements/announcement_id/Comments/comment_id/Replies/reply_id)");
Pattern p = Pattern.compile("(?:Announcements/([^/]*))(?:/Comments/([^/]*))?(?:/Replies/([^/]*))?\\)");
list.forEach(x -> {
Matcher m = p.matcher(x);
if (m.matches()) {
System.out.println("For string '" + x + "' --> announcement_id: " + m.group(1) + ", commend_id: "
+ m.group(2) + ", reply_id: " + m.group(3));
}
});
根据找到的内容适当打印数据,
For string 'Announcements/announcement_id)' --> announcement_id: announcement_id, commend_id: null, reply_id: null
For string 'Announcements/announcement_id/Comments/commend_id)' --> announcement_id: announcement_id, commend_id: commend_id, reply_id: null
For string 'Announcements/announcement_id/Comments/comment_id/Replies/reply_id)' --> announcement_id: announcement_id, commend_id: comment_id, reply_id: reply_id
答案 1 :(得分:1)
您的pathParams顺序是预先定义的,因此请使用split并解析数组。
String s = "Announcements/announcement_id/Comments/comment_id/Replies/reply_id)";
String [] pathParams = s.split("/");
答案 2 :(得分:1)
String s = "Announcements/announcement_id/Comments/comment_id/Replies/reply_id";
String[] h = s.split("\\/");
switch (h.length) {
case 2:
System.out.println(h[1]);
break;
case 4:
System.out.println(h[1] + " " + h[3]);
break;
case 6:
System.out.println(h[3] + " " + h[5]);
break;
default:
break;
}
此代码还提供了一种在拆分后如何继续以及访问所需元素的方法
答案 3 :(得分:0)
以下方法适用于更多路径
String s = "Announcements/announcement_id/Comments/comment_id/Replies/reply_id)";
String[] paths = s.split("/");
if (paths.length % 2 == 0) {
if (paths.length == 2) {
System.out.println(paths[1]);
} else {
int lastPos = paths.length - 1;
int beforeLastPos = lastPos - 2;
System.out.println(paths[beforeLastPos] + " " + paths[lastPos]);
}
}