RegEx 根据运算符拆分字符串并保留运算符作为答案 [英] RegEx to split string based on operators and retain operator in answer
本文介绍了RegEx 根据运算符拆分字符串并保留运算符作为答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据几个操作数拆分字符串.
I want to split string based on few operands.
例如字符串:a&&(b||c)
For e.g.
String : a&&(b||c)
ANS : String[] {a,&&,(,||,c,)}
ANS : String[] {a,&&,(,||,c,)}
Java 正则表达式可以吗?如果是,那么如何?
IS it possible with java RegEx? If yes then how?
我尝试使用 [&&||()] regEx ,但它没有给出所需的输出.甚至我都不知道如何留住运营商.
I tried with [&&||()] regEx , but its not giving desired output. and even I am not sure how to retain operators.
如果我们有 &和|而不是 &&和 ||?
And what if we have & and | instead of && and || ?
推荐答案
您可以拆分:
(?<![&|])(?=[&|])|(?<=[&|])(?![&|])
(?<![&|])(?=[&|])
的意思是任何inter-char不是 前面是&
或|
但is 后面是&
或|
";- 相反,
(?<=[&|])(?![&|])
表示任何inter-charis 前面有&
或|
但ist 后跟&
或|
". (?<![&|])(?=[&|])
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|
".
例如:
String pattern = "(?<![&|])(?=[&|])|(?<=[&|])(?![&|])";
String input = "a&&(b||c)";
String[] array = input.split(pattern);
System.out.println(Arrays.asList(array));
打印:
[a, &&, (b, ||, c)]
这篇关于RegEx 根据运算符拆分字符串并保留运算符作为答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文