我想使用正则表达式拆分字符串,并将分隔符/匹配的信息包含在生成的数组中。
在Java中,我使用了:
但是,JavaScript 不支持正则表达式的后顾断言
例如,我想要匹配字符串:
分割:
我得到的例子是:
在Java中,我使用了:
theString.split("(?<=[!><=}{])|(?=[!><=}{])|(?<= AND )|(?= AND )|(?<= OR )|(?= OR )")
但是,JavaScript 不支持正则表达式的后顾断言
?<=
。例如,我想要匹配字符串:
"Reason={Existing problem or fault}{Bestaande probleem of vout}{Other}{Ander} and Required!=No and Results >=10 and Results <=25 and Tst>5 and Tst<80 and Info=test this or that and those and Success!=Yes"
分割:
Reason,=,{,Existing problem, or ,fault,},{,Bestaande probleem of vout,},{,Other,},{,Ander,}, and ,Required,!,=,No, and ,Results,>,=,10, and ,Results,<,=,25, and ,Tst,>,5, and ,Tst,<,80, and ,Info,=,test this, or ,that, and ,those, and ,Success,!,=,Yes
我得到的例子是:
var thestr = "Reason={Existing problem or fault}{Bestaande probleem of vout}{Other}{Ander} and Required!=No and Results >=10 and Results <=25 and Tst>5 and Tst<80 and Info=test this or that and those and Success!=Yes";
document.write("::SPLIT::<br>");
var patt1=new RegExp(/([!><=}{])|( AND )|( OR ) /gi);
var x = thestr.split(patt1);
//This splits correctly but, doesn't include the separators / matched characters
document.write("length="+x.length+"<br>");
for (c=0;c<x.length;c++) {
document.write(c+" - "+ x[c]+" |");
}
document.write("<br><br>::MATCH::<br>");
var y = thestr.match(patt1);
//This shows the matched characters but, how do I combine info from split and match
document.write("length="+y.length+"<br>");
for (d=0;d<y.length;d++) {
document.write(d+" - "+ y[d]+" |");
}
document.write("<br><br>::INCLUDE SEPERATORS::<br>");
var patt2=new RegExp(/(?![!><=}{])|(?=[!><=}{])|(?! AND )|(?= AND )|(?! OR )|(?= OR ) /gi);
//This puts everything in the array, but, each character is a seperate array element.
// Not what I wanted to achieve.
var bits = thestr.split(patt2);
document.write("length="+bits.length+"<br>");
for (r=0;r<bits.length;r++) {
document.write(r+" - "+ bits[r]+" |");
}
或
,和
, 以及任何两个字符之间拆分,除了字母数字字符或空格之间? - Tim Pietzcker