2012-09-05 50 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