问题
I want to split string based on few operands.
For e.g.
String : a&&(b||c)
ANS : String[] {a,&&,(,||,c,)}
IS it possible with java RegEx? If yes then how?
I tried with [&&||()] regEx , but its not giving desired output. and even I am not sure how to retain operators.
EDIT: And what if we have & and | instead of && and || ?
回答1:
You could split by:
(?<![&|])(?=[&|])|(?<=[&|])(?![&|])
- (?<![&|])(?=[&|])means "any inter-char that isn't preceded by- &or- |but that is followed by- &or- |";
- On the opposit, (?<=[&|])(?![&|])means "any inter-char that is preceded by&or|but that isn't followed by&or|".
For example:
String pattern = "(?<![&|])(?=[&|])|(?<=[&|])(?![&|])";
String input = "a&&(b||c)";
String[] array = input.split(pattern);
System.out.println(Arrays.asList(array));
Prints:
[a, &&, (b, ||, c)]
回答2:
You need to provide a list of "operands", e.g.:
[0-9]|[a-z]|[A-Z]|\|\||&&|\(|\)
Each non-escaped | defines new operand. You need to escape some operands which are keywords by adding \. 
Then you need to use find of java.util.regex.Matcher. to get each operand.
来源:https://stackoverflow.com/questions/17105299/regex-to-split-string-based-on-operators-and-retain-operator-in-answer