1
String s = "A..?-B^&';(,,,)G56.6C,,,M4788C..,,A1''";
String[] result = s.split("(?=[ABC])");
System.out.println(Arrays.toString(result));

Output:

 [A..?-, B^&';(,,,)G56.6, C,,,M4788, C..,,, A1'']

Please refer to the The split in the above case. I am trying to separate strings based on A, B orC. How can I get the the same split strings into an ArrayList using pattern matcher? I could not figure out how to group in the below code.

Pattern p = Pattern.compile("(?=[ABC])");
Matcher m = p.matcher(s);
List<String> matches = new ArrayList<>();
while (m.find()) {
   matches.add(m.group());
}

Also suppose I have few characters before first occurance of A, B or C and I want to combine with first element in ArrayList. ,,A..

Appreciate the help.

2
  • Why don't you want to use your first solution? Commented Sep 12, 2014 at 12:42
  • Can't you use String[] result = Pattern.compile("(?=[ABC])").split(s, 0); ? Commented Sep 12, 2014 at 12:47

1 Answer 1

4
[ABC][^ABC]*

If I didn't ommit any edge case that should work with the code you provided

For the extra question, you could possibly add (^[^ABC]*)* to the beggining, but that makes it slower and look less readable, not to mention it will only work for single-line strings to check. I would recommend just parsing the beggining characters manually, treating it like a special case it is.

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer's much better than mine. +1 and deleting.

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.