0 0

java中正则的问题5

java中使用split分割字符串:怎么用正则匹配“@”、“;”、“:”但是不匹配双引号和单引号之间的内容,例如:String s ="qq@q'q@q'q;\"qqq@@qqq\"q;qq";这个字符串 拆分 完了应该是:qq 、q'q@q'q、"qqq@@qqq"q和qq
2012年7月01日 21:04

5个答案 按时间排序 按投票排序

1 0

这个用正则效率应该就低了。
大概用这种带回溯的。比如 ?>(\')@
还不如自己写个小函数, 遍历一遍就over了
该分割分割,该压栈压栈。

2012年7月02日 01:58
0 0

split的确不好解决,
使用indexof好解决的多
String s ="qq@q'q@q'q;\"qqq@@qqq\"q;qq";
如先按@分开:
int index1=s.indexof("@");
String s1=s.substring(0, index1);
s=s.substring(index1+1);
再按;分开
int index2=s.indexof(";");
String s2=s.substring(0, index2);
s=s.substring(index2+1);
......
以此类推,这种方法应该比较简单

2012年7月02日 13:48
0 0

split做不到,但是正则表达式还是可以做到的,你可以把代码再封装一下。

/**
	 * @param args
	 */
	public static void main(String[] args) {
		String s = "qq@q'q@q'q;\"qqq@@qqq\"q;qq";
		String regex = "(([^'\"]+?)|([^']*?'[^']*?'[^']*?)|([^']*?\"[^']*?\"[^']*?))([@;:]|$)";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(s);
		while (m.find()) {
			System.out.println("==" + m.group(1));
		}

	}

2012年7月02日 10:22
0 0

	public static String[] split(String s) {
		ArrayList<String> list = new ArrayList<String>();
		int n = s.length();
		int beginIndex = 0;
		boolean hasQuot = false;
		for (int i = 0; i < n; i++) {
			char ch = s.charAt(i);
			switch (ch) {
			case '\'':
			case '"':
				hasQuot = !hasQuot;
				break;
			case '@':
			case ';':
			case ':':
				if (!hasQuot) {
					list.add(s.substring(beginIndex, i));
					beginIndex = i + 1;
				}
				break;
			}
		}
		if (beginIndex < n)
			list.add(s.substring(beginIndex));
		return list.toArray(new String[list.size()]);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String s = "qq@q'q@q'q;\"qqq@@qqq\"q;qq";
		String[] a = split(s);
		for (String str : a) {
			System.out.println(str);
		}
	}

2012年7月02日 10:13
0 0

那就分两次split好了,先按照',"来split一次,再按照“@”、“;”、“:”再来split一次不就好了么
var tmp = s.split(/[\'\"]+/);
var arr;
for (i = 0; i < arr.length;i++) {
    arr = arr.concat(tmp[i].split(/[@、:]+/));
}

2012年7月02日 08:50

相关推荐

Global site tag (gtag.js) - Google Analytics