對於規則如何存儲鍵值和分隔符在Java
a==b&c>=d|e<=f&!x==y
我想分割使用&規則,| &,!運營商也不希望存儲運營商。
所以我想存儲:
a==b
&
c>=d
|
e<=f
&!
x==y
而且我應該存儲在這一個字符串數組?
謝謝。
對於規則如何存儲鍵值和分隔符在Java
a==b&c>=d|e<=f&!x==y
我想分割使用&規則,| &,!運營商也不希望存儲運營商。
所以我想存儲:
a==b
&
c>=d
|
e<=f
&!
x==y
而且我應該存儲在這一個字符串數組?
謝謝。
嘗試這種方式
String data = "a==b&c>=d|e<=f&!x==y";
Pattern p = Pattern.compile(
"&!"+ // &!
"|" + // OR
"&" + // &
"|" + // OR
"\\|" // since | in regex is OR we need to use to backslashes
// before it -> \\| to turn off its special meaning
);
StringBuffer sb = new StringBuffer();
Matcher m = p.matcher(data);
while(m.find()){
m.appendReplacement(sb, "\n"+m.group()+"\n");
}
m.appendTail(sb);
System.out.println(sb);
輸出
a==b
&
c>=d
|
e<=f
&!
x==y
此正則表達式你想要做什麼..
final String input = "a==b&c>=d|e<=f&!x==y";
//this regex will yield pairs of one string followed by operator (&, | or &!)...
final String mainRegex = "(.*?)(&!|&|\\|)";
final Matcher matcher = Pattern.compile(mainRegex).matcher(input);
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
//...so we will need another regex to fetch what comes after the last operator
final String lastOne = "(.*)(&|\\||!)(.*)";
final Matcher lastOneMatcher = Pattern.compile(lastOne).matcher(input);
if (lastOneMatcher.find()) {
System.out.println(lastOneMatcher.group(3));
}
結果:
a==b
&
c>=d
|
e<=f
&!
x==y
它可以在一行中實現,但它會涉及一個相當複雜的正則表達式,既使用lookahead也使用lookbehead。
str.split("(?<=&!?|\\|)|(?=&!?|\\|)");
那麼這個正則表達式是做什麼的?
正則表達式&!?|\|
根據您的規則定義了什麼是有效的運算符。它基本上讀出爲「並且&
- 可選地後面跟着!
-簽名,或者 --簽名」。
其他部分是正則表達式構造向前看和向後看,這就是所謂的「零寬度斷言」。 (?=a)
是一個向前看,並確保下一個字符是「a」的向前看。例如。它匹配 在「foobar」中的「b」和「a」之間開始和結束的零長度字符串。
因此,與給定的正則表達式的說法,我提出的分割方法調用基本上沒有:
分割在輸入字符串中的每個位置,並立即開始之前或之後&
,一個&!
或|
跡象。
以任何適合您的程序的方式存儲它。你爲什麼需要拆分它?這是唯一需要拆分的字符串嗎?還有其他類似的東西需要拆分嗎? – 2012-08-16 14:45:43
您是否在尋找一種可以實現您所描述的標準API? – Vikdor 2012-08-16 14:49:00
規則可以有&,|,&!.像a == b等操作數可以改變。 – SUM 2012-08-16 14:49:07