0

how can I extract string between [" "] I have eg: ["x"], so how can I extract just x and assign it to a variable I have tried this:

String str = "[x]";    
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

I can get x using the above code but my string is enclosed between [" "]

user123
  • 243
  • 4
  • 10

4 Answers4

1

The easiest way would be the following:

String s = "aaaa [\"axas\"]";
String result = s.substring(s.indexOf("[\"")+2, s.indexOf("\"]"));

\" stands for a character " - \ is an escape character and it is the missing part in your solution.

enter image description here

results in:

enter image description here

xenteros
  • 15,586
  • 12
  • 56
  • 91
  • Your code works fine. but in my situation, x is a json object which I am extracting using json path extractor in jmeter and the result when extracted is `name=["x"]`. So how can I append those `/` since the result I get when extracted is in this pattern `["x"]` only – user123 Jun 06 '17 at 20:29
0

This regexp seems to work:

final String regexpStr = "\\[\"(.*?)\"\\]";

JUnit test for it:

@Test
public void regexp() {
    final String[] noMatch = { "", "[", "[\"", "]", "\"]", "\"[", "]\"", "asdf",
            "[\"asdfasdf\"", "asdf[sadf\"asdf\"]" };
    final String[] match = { "[\"one\"]", "asdf[\"one\"]", "[\"one\"]asdf", "asdf[\"one\"]asdf",
            "asdf[\"one\"]asdf[\"two\"]asdf" };
    final String regexpStr = "\\[\"(.*?)\"\\]";

    final Pattern pattern = Pattern.compile(regexpStr);
    for (final String s : noMatch) {
        final Matcher m = pattern.matcher(s);
        Assert.assertFalse(m.matches());
    }

    for (final String s : match) {
        final Matcher m = pattern.matcher(s);
        Assert.assertTrue(m.find());
        Assert.assertEquals(m.group(1), "one");
        if (m.find()) {
            Assert.assertEquals(m.group(1), "two");
        }
    }
}
nCessity
  • 735
  • 7
  • 23
-1
package soquestion;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SOQuestion {

    public static void main(String[] args) {
        String str = "[\"foo\"] and [\"bar\"]";
        System.out.println("String is: " + str);
        Pattern p = Pattern.compile("\\[\\\"(.*?)\\\"\\]");
        Matcher m = p.matcher(str);
        while (m.find()) {
            System.out.println("Result: " + m.group(1));
        }            
    }

}

Results in:

String is: ["foo"] and ["bar"]
Result: foo
Result: bar
Martijn Burger
  • 7,315
  • 8
  • 54
  • 94
-2

Use the following code:

public static void main(final String[] args) {
    String in = "[ABC]";

    Pattern p = Pattern.compile("\\[(.*)\\]");
    Matcher m = p.matcher(in);

    while(m.find()) {
        System.out.println(m.group(1));
    }
}
kk.
  • 3,747
  • 12
  • 36
  • 67