RXC
RXC

Reputation: 1233

Java split method using Regex

I have a string being passed into a function. The string looks like this: "[teststring]"

There are cases where there may be multiple string in there separated by a delimiter. "[teststring, nogood; dontUse]"

How can I use the java split method to extract the first string, excluding the brackets and the delimiters can be either a comma and/or semi-colon?

This does not work:

string args = "[teststring, nogood; dontUse]";
string temp = args.split("[,;]")[0];

The final result should be just: teststring.

Upvotes: 0

Views: 215

Answers (3)

aelor
aelor

Reputation: 11116

You can use a simple regex to get the capture group in javascript

var str = "[teststring, nogood; dontUse]";
var res = /(\w+)/.exec(str);
console.log(res[1]);

Upvotes: -1

Pshemo
Pshemo

Reputation: 124235

Instead of split you can create pattern which will find substring which is right after [ and contains only characters that are not delimiters. Here is example

String data = "[teststring, nogood; dontUse]";
Pattern p = Pattern.compile("\\[([^,;]+)");
Matcher m = p.matcher(data);
if (m.find())
    System.out.println(m.group(1));

Output:

teststring

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208485

Your current approach will split on , and ; and grab the first element, so in this case you will get everything before the comma and the result will be "[teststring". To just get "teststring" you will want to split on the square brackets as well, and then grab the second element instead of the first (since the first element will now be the empty string before the [). For example:

String args = "[teststring, nogood; dontUse]";
String temp = args.split("[\\[\\],;]")[1];

Upvotes: 2

Related Questions