2017-08-02 358 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方法来获得所需的输出。

相关问题