[英]How to extract string between two strings using java Pattern
我有一个字符串 /subscription/ffcc218c-985c-4ec8-82d7-751fdcac93f0/subscribe,我想从中提取中间字符串 /subscription/<....>/subscribe。 我写了下面的代码来获取字符串
String subscriber = subscriberDestination.substring(1);
int startPos = subscriber.indexOf("/") + 2;
int destPos = startPos + subscriber.substring(startPos + 2).indexOf("/");
return subscriberDestination.substring(startPos, destPos + 2);
返还ffcc218c-985c-4ec8-82d7-751fdcac93f0
如何使用 java Pattern 库编写更好的代码?
如果要使用正则表达式,一种简单的方法是:
return subscriber.replaceAll("/.*/([^/]*)/.*", "$1");
/.*/
用于/subscription/
位 ([^/]*)
匹配所有字符的捕获组,直到下一个/
/.*
用于/subscribe
位 replaceAll
的第二个参数表示我们要保留第一组。
您可以使用Pattern
通过编译表达式来提高效率:
Pattern p = Pattern.compile("/.*/([^/]*)/.*"); ///store it outside the method to reuse it
Matcher m = p.matcher(subscriber);
if (m.find()) return m.group(1);
else return "not found";
离我5c。 我建议使用Pattern
提取已知格式的子字符串:
public final class Foo {
private static final Pattern PATTERN = Pattern.compile(".*subscription\\/(?<uuid>[\\w-]+)\\/subscribe");
public static String getUuid(String url) {
Matcher matcher = PATTERN.matcher(url);
return matcher.matches() ? matcher.group("uuid") : null;
}
}
可以通过以下方法提高性能:
substring
。 同样,使用char
indexOf(..)
应该比使用String
更快。
final int startPos = subscriberDestination.indexOf('/',1) + 1 ; final int destPos = subscriberDestination.indexOf('/',startPos+1); return subscriberDestination.substring(startPos, destPos );
关于使用java Pattern library
:
您期望性能有所提高吗? 我怀疑您会通过使用Java Pattern库获得一些东西。 但是我建议对其进行概要分析,以确保对此有绝对的把握。
您可以使用其他方法
String test = "abc/azerty/123";
字符串[] r = test.split(“ /”);
您的结果在r [1]中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.