RegEx to split string based on operators and retain operator in answer

我的梦境 提交于 2019-12-25 01:45:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!