我有这个字符串:
"http://my/website/collections/index.php?s=1&schema=http:/my/web/fe7cd50991b11f51050902sddaf3e042bd5467/idApp=19"
我想从字符串中提取这个标记:fe7cd50991b11f51050902sddaf3e042bd5467
网站可能会有所不同,但唯一不能改变的是我必须获取的字符串令牌始终位于“/idApp =”的左侧
解决这个问题的最有效方法是什么?
谢谢。
String url = "http://my/website/collections/index.php?s=1&schema=http:/my/web/fe7cd50991b11f51050902sddaf3e042bd5467/idApp=19";
String[] tokens = url.split("/");
String searched = tokens[array.length - 2];
如果令牌每次都是 prelast,这将起作用。否则,您需要通过Array并检查当前令牌是否符合您的条件并在之前获取令牌。在代码中:
int tokenId = 0;
for (int i = 0; i < tokens.length; i++) {
if (token[i].equals("/idApp=")) {
tokenId = i - 1;
break;
}
}
String rightToken = tokens[tokenId];
假设令牌只能是数字和字母,你可以使用这样的东西。
它匹配 /idApp= 字符串之前的一系列数字和字母。
就作为一种标准的、易于阅读的方式而言,它是“高效的”,但可能有更高效的方式来做到这一点,尽管您应该仔细考虑找到这个字符串是否真的是一种性能瓶颈。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegexp {
public static void main(String args[]) {
String text = "http://my/website/collections/index.php?s=1&schema=http:/my/web/fe7cd50991b11f51050902sddaf3e042bd5467/idApp=19";
Pattern pattern = Pattern.compile("(\\w+)/idApp=");
Matcher m = pattern.matcher(text);
if (m.find()) {
System.out.println(m.group(1));
}
}
}
您在这里不需要正则表达式。绝对地。任务只是剪断一根绳子,不要过于复杂。简单是关键。
int appIdPosition = url.lastIndexOf("/idApp=");
int slashBeforePosition = url.lastIndexOf("/", appIdPosition - 1);
String token = url.substring(slashBeforePosition + 1, appIdPosition);
你可以使用正则表达式
这两个包可以帮助你
java.util.regex.Matcherjava.util.regex.Pattern使用字符串做任何事情时,请始终注意:
http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html
这是我的答案...
public static void main(String[] args) {
//Don't forget: import static org.apache.commons.lang.StringUtils.*;
String url2 = "http://my/website/collections/index.php?s=1&schema=http:/my/web/fe7cd50991b11f51050902sddaf3e042bd5467/idApp=19";
String result = substringAfterLast("/", substringBeforeLast(url2,"/")) ;
System.out.println(result);
}
简单的 2 次拆分适用于多个参数。先拆开"idApp"再开/。
即使参数后面有多个参数,以下代码也可以工作idApp。
String url = "http://my/website/collections/index.php?s=1&schema=http:/my/web/fe7cd50991b11f51050902sddaf3e042bd5467/idApp=19";
String[] tokens = url.split("idApp");
String[] leftPartTokens = tokens[0].split("/");
String searched = leftPartTokens[leftPartTokens.length - 1];
System.out.println(searched);