2012-09-05 48 views
0

我有这个字符串:分割字符串小问题

"http://my/website/collections/index.php?s=1&schema=http:/my/web/fe7cd50991b11f51050902sddaf3e042bd5467/idApp=19" 

我想提取从字符串此令牌:fe7cd50991b11f51050902sddaf3e042bd5467

的网站上可以有所不同,但唯一想到的不能改变的是,该字符串令牌我必须总是在左边的“/ idApp =”

哪个是解决这个问题的最有效的方法?

感谢。

+0

正则表达式? – Vic

+1

你试过的是什么? – Sujay

回答

3
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]; 
0

你可以使用正则表达式

这两个包将帮助您

  • java.util.regex.Matcher
  • java.util.regex.Pattern
+1

您可能想详细说明您的答案,并向OP提供解决方案,而不是仅讨论可用包:) – Sujay

2

假设令牌只能数字和字母,您可以使用这样的事情。

它匹配/ 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)); 
     } 

    } 
} 
1

这里不需要regexp。绝对。这个任务只是为了剪下一段字符串,不要过分复杂。简单是关键。

int appIdPosition = url.lastIndexOf("/idApp="); 
int slashBeforePosition = url.lastIndexOf("/", appIdPosition - 1); 
String token = url.substring(slashBeforePosition + 1, appIdPosition); 
0

简单的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); 
0

在做用绳子任何事情,总是垂青:

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); 
} 
+0

虽然答案是完全有效的,但我不会建议OP使用静态导入。 [静态导入方法的好用例是什么?](http://stackoverflow.com/q/420791/851811) –

+0

你是对的,静态导入不是必须的,但在我看来,它使代码更少详细和大多数IDE会告诉我们代码来自哪里。我通常对StringUtils进行静态导入,因为我倾向于大量使用它,Oracle说“当您需要频繁访问来自一个或两个类的静态成员时使用它”。 – Nos