0

I want to separate a string but to keep separators except space.

Also I'd like to not separate words like asda45a or asd6ad.

this is the list of separators:

private static String delimits="[{;}(),#<>*+-=/ ]+";

I tried String[] List = o.split("(?<="+delimits+")|(?="+delimits+")");

3
  • Could you provide a sample of a full string you would use this on? Commented Nov 6, 2016 at 14:16
  • also what do you mean by words like asda45a or asd6ad? Commented Nov 6, 2016 at 14:45
  • Words with numbers, I try to make a lexical analyzer. Commented Nov 6, 2016 at 16:03

1 Answer 1

1

You need to adjust your delimits pattern to exclude the space (since you do not want to keep space delimiters in the result) and put the - at the end of the character class as in your expression it forms a range between + and =. Then, just add an | + alternative to the main regex:

String delimits="[{;}(),#<>*+=/-]+";
String o = "asda45a or-ro asd6ad";
String[] lst = o.split("(?<="+delimits+")|(?="+delimits+")| +");
System.out.println(Arrays.toString(lst));
// => [asda45a, or, -, ro, asd6ad]

See the online Java demo

If you want to split with any whitespace, replace | + with |\\s+.

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

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.