我有一个表达式字符串
"((firstname = john AND Lastname = Eleven) OR (salary = 15000 AND location = Mexico OR (firstname = mathew AND lastname = Thirteen)))";
是否有任何内置函数我可以将它们拆分为List<String>
,格式如下:
list[0] = "(";
list[1] = "(";
list[2] = "firstname";
list[3] = "=";
list[4] = "john"
list[5] = "AND";
list[6] = "Lastname"
list[7] = "=";
list[8] = "Eleven";
list[9] = ")"
list[10] = "OR"
list[11] = "(";
list[12] = "salary";
list[13] = "15000"
list[14] = "AND"
etc...
答案 0 :(得分:3)
您可以替换所有(
或)
woth space $1 space
,然后用空格分割:
String spl[] =
str.replaceAll("([\\(\\)=])", " $1 ").replaceAll(" +", " ").trim().split("\\s");
<强>输出强>
(, (, firstname, =, john, AND, Lastname, =, Eleven, ), OR, (, salary, =, 15000, AND,
location, =, Mexico, OR, (, firstname, =, mathew, AND, lastname, =, Thirteen, ), ), )
答案 1 :(得分:1)
只需将split
与多个分隔符
String[] tokens = exp.split("\\(|\\)| |=");
答案 2 :(得分:1)
通常,此过程称为lexical analysis:
在计算机科学中,词法分析是将一系列字符(例如在计算机程序或网页中)转换为的过程令牌(具有指定且因此标识的含义的字符串)
可以定义lexical grammar:
词汇语法是一种形式语法定义标记的语法
一旦定义了词汇语法,就可以使用像JavaCC或JFlex这样的工具,在词法分析器中转换该语法,这基本上是一个软件,它将一系列字符作为输入,并生成一个令牌列表作为输出。
请注意,词法分析器不仅会在字符串序列中分割原始的字符序列,而且会在更具体的标记序列中分割,例如:
OPEN_PARANTHESIS
OPEN_PARANTHESIS
NAME with value firstname
OPERATOR with value =
NAME with value john
OPERATOR with value AND
NAME with value Lastname
OPERATOR with value =
...
所以它做的比你提出的更多,但你的问题似乎与它有关。
答案 3 :(得分:0)
您可以将lookahead
和lookbehind
与regex
一起使用来获取令牌并对其进行迭代,例如:
String s = "((firstname = john AND Lastname = Eleven) OR (salary = 15000 AND location = Mexico OR (firstname = mathew AND lastname = Thirteen))";
for(String token : s.split("((?=(\\(|\\)|\\=|\\sAND\\s|\\sOR\\s))|(?<=(\\(|\\)|\\=|\\sAND\\s|\\sOR\\s)))")){
System.out.println(token.trim());
}
答案 4 :(得分:-1)
"((firstname = john AND Lastname = Eleven) OR (salary = 15000 AND location = Mexico OR (firstname = mathew AND lastname = Thirteen)))";
在“((
”之间添加如下空格:
String exp = "( ( firstname = john AND Lastname = Eleven ) OR ( salary = 15000 AND location = Mexico OR ( firstname = mathew AND lastname = Thirteen ) ) )";
现在您可以使用exp.split( " ");