-1

I want to extract subString from a String, starting from __(Double UnderScore) till a "(Double Quotes) or special character '[](),' is found.

I have been at it for some while now but cannot figure it out.

For Example: Input String : "NAME":"__NAME"

Required String : __NAME

Thanks for your time.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    1. find the position of `__` 2. substring from that position. 3. in the new string: find the position of `"`. 4. substring until that position – ParkerHalo Aug 02 '17 at 10:42

3 Answers3

4

You can use this regex (__(.*?))[\"\[\]\(\),] to get what you want you can use :

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

Output

__NAME

regex demo

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

You could try following code

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

May this solution help you:

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

In this firstly we calculate the index of __ and then we calculate the index of " after __.and then use substring method to get desired output.

Rohit-Pandey
  • 2,039
  • 17
  • 24