日期:2014-05-18 浏览次数:20960 次
var s = "[基本工资]+[奖金]-[保险]"; var ret = splitX(s); for (var i = 0; i < ret.length; i++) { alert(ret[i]); } function splitX(s) { var ret = new Array(); if (s == null || s == "") { return ret; } var idx1, idx2, i = 0; while ((idx1 = s.indexOf("[")) > -1 && idx1 != s.length - 1) { idx2 = s.indexOf("]"); if (idx2 > idx1) { ret[i] = s.substring(idx1 + 1, idx2); i++; s = s.substring(idx2); } else { s = s.substring(idx1); } } return ret; }
------解决方案--------------------
用正则最简单,也最正规!
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { Pattern p = Pattern.compile("\\[(.*?)\\]"); String str = "[基本工资]+[奖金]-[保险]"; Matcher m = p.matcher(str); while (m.find()) { System.out.println(m.group(1)); } } }
------解决方案--------------------
function test(){ var reg = /\[(.*?)\]/gi; var str = "[基本工资]+[奖金]-[保险]"; var tmp = str.match(reg); if (tmp) { for (var i = 0; i < tmp.length; i++) { alert(tmp[i]); // 保留中括号 alert(tmp[i].replace(reg, "$1")); // 不保留中括号 } } else { alert("no match."); } }