0

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.

4
  • 3
    Before asking Will this work, try it. Commented Feb 12, 2014 at 19:58
  • Almost there just remember about the bracket. Good luck. Commented Feb 12, 2014 at 20:00
  • One issue is that you have a : in the regex, instead of a ;. Commented Feb 12, 2014 at 20:00
  • using guava: List<String> parts = Splitter.on(CharMatcher.anyOf("[,:]").omitEmptyStrings().trimResults().split(input) Commented Feb 12, 2014 at 20:03

3 Answers 3

2

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];
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.