2017-08-02 273 views
-1

我想從字符串中提取子字符串,從__(Double UnderScore)開始,直到找到"(雙引號)或特殊字符'[](),'從字符串獲取子字符串__

我已經有一段時間了,但無法弄清楚。

例如:輸入字符串:"NAME":"__NAME"

String類型,必需:__NAME

感謝您的時間。

+1

1.從該位置查找'__' 2的位置。 3.在新字符串中:找到'「'的位置。4.子字符串直到該位置 – ParkerHalo

回答

4

您可以使用此正則表達式(__(.*?))[\"\[\]\(\),]得到你想要的東西,你可以使用:

String str = "\"NAME\":\"__NAME\""; 
String regex = "(__(.*?))[\"\\[\\]\\(\\),]"; 
Pattern pattern = Pattern.compile(regex); 
Matcher matcher = pattern.matcher(str); 

while (matcher.find()) { 
    System.out.println(matcher.group(1)); 
} 

輸出

__NAME 

regex demo

0

你可以試試下面的代碼

String input="\"NAME\":\"__NAME\""; 
int startIndex=input.indexOf("__"); 
int lastIndex=input.length(); 
String output=input.substring(startIndex, (lastIndex-1)); 
System.out.println(output); 
+0

我認爲來自@ParkerHalo的算法描述了一個更好的解決方案... –

0

可能該解決方案幫助您:

import java.util.*; 
class test 
{ 
    public static void main(String[] args) { 
     Scanner s=new Scanner(System.in); 
     String a=s.next(); 
     int i=a.indexOf("__"); 
     int j=a.indexOf('"',i); 
     System.out.println(a.substring(i,j)); 
     } 
} 

在此首先我們計算的__的索引,然後我們__後計算"指數。而再使用substring方法來獲得所需的輸出。