john
john

Reputation: 11709

How to extract strings from a string which has bracket?

I have a string like this -

(a,b=7)

How can I extract a, b and 7 from the above string. I need to pass those values to my constructor.

Graph.Edge("a", "b", 7)

Is there any easy way to do this? Do I need to use regex for this?

Upvotes: 0

Views: 64

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174844

You could use string.split method.

String s = "(a,b=7)";
String parts[] = s.split("\\W+");
ArrayList<String> list = new ArrayList<String>(Arrays.asList(parts));
list.removeAll(Arrays.asList("", null));
System.out.println(list);

Output:

[a, b, 7]

Upvotes: 1

aioobe
aioobe

Reputation: 421290

Using regular expressions you could do:

String str = "(a,b=7)";

Pattern p = Pattern.compile("\\((.*?),(.*?)=(\\d+)\\)");
Matcher m = p.matcher(str);
if (m.matches()) {
    System.out.println(m.group(1));                    // a
    System.out.println(m.group(2));                    // b
    System.out.println(Integer.parseInt(m.group(3)));  // 7
}

Upvotes: 1

Related Questions