Java字符串分割函数split中以·点分割的问题

  • Post author:
  • Post category:java


问题描述:


// 把字符串


“192.168.1.1”按照小圆点进行分割,分割成”192″,”168″,”1″,”1″四个字符串。

String preStr = “192.168.1.1”;


String[] string = preStr.split(“.”); //


错误写法。


这种写法得到的字符串组长度为0


String[] string = preStr.split(“\\.”); //



正确写法。


对小圆点进行转义








出现上述情况的原因是:split函数会将参数看作是正则表达式进行处理。”.”在正则表达式中表示匹配任意一个字符,经过转义之后,”.”才是本身的含义,才能得到正确的分割结果。下面主要探讨上述错误写法中得到的字符串组为什么大小为0。



下面是split函数源代码(




java




.




util




.




regex




.




Pattern




.split






public String[] split(CharSequence input, int limit) {
		int index = 0;
		boolean matchLimited = limit > 0; // 是否限制匹配个数
		ArrayList<String> matchList = new ArrayList<String>(); // 匹配结果队列
		Matcher m = matcher(input); // 待切割字符(串)匹配对象
		// Add segments before each match found
		while (m.find()) {
			// 如果不限制匹配个数 或者 当前结果列表的大小小于limit-1
			if (!matchLimited || matchList.size() < limit - 1) {
				String match = input.subSequence(index, m.start()).toString(); // 取子串,(分隔串所在的首位)
				matchList.add(match); // 添加进结果集
				index = m.end(); // 获取下一个子串的首字符下标
			} else if (matchList.size() == limit - 1) { // last one,即还剩最后一个名额了
				// 最后一个元素从指针取到字符串结尾
				String match = input.subSequence(index, input.length()).toString();
				matchList.add(match);
				index = m.end();
			}
		}
		// If no match was found, return this
		if (index == 0) // 即没有切分到的意思吧,返回整一串
			return new String[] { input.toString() };
		// 如果不限制匹配个数 或者结果集大小小于限制个数
		if (!matchLimited || matchList.size() < limit)
			// 最后一个元素从指针取到字符串结尾
			matchList.add(input.subSequence(index, input.length()).toString()); // Construct
		// result
		int resultSize = matchList.size();
		if (limit == 0)
			// 如果结果集最后的元素是"",一个一个地删除它们
			while (resultSize > 0 && matchList.get(resultSize - 1).equals(""))
			resultSize--;
		String[] result = new String[resultSize];
		return matchList.subList(0, resultSize).toArray(result);
	}

代码中注释转自https://www.cnblogs.com/xzhang/p/3995464.html

正则表达式中“.”表示匹配任意一个字符。对于split函数而言,就是就是以任意字符为分隔符进行分割,那么“192.168.1.1”按照任意字符分割等价于“ccccccccccc”按照“c”进行分割,那么分割结果肯定都是空串。split函数中最后的while循环会将分割之后的字符串组,从后往前清理空字符串,所以“.”在不转义的情况下,分割字符串得到的结果为空。

代码中,Matcher m = matcher(input)中,m记录下每个分隔符的位置。例如“abc;efg;hig”中,分隔符“;”的位置是3,7。m.start()可以获取到第一个分隔符的索引3,利用函数


subSequence(




int start,




int end)


进行分割,所以第一个子串传入参数[start = 0,end = 3],m.end()获取当前匹配到的分隔符之后的位置4;m.find()寻找下一个分隔符位置,m.start()为7,第二个字串[start = 4,end = 7];以此类推。

对于字符串“192.168.1.1”按照“.”进行分割时,分隔符的位置为0,1,2,3,4,…,10,11,每个子串是[0,0],[1,1][2,2],…,[10,10],[11,11]。对于函数


subSequence(






int start,






int end)


,end==start时返回空串。所以最后得到的结果也是空串。

以上是一些简单分析,有不对的地方请大家多指教。

下面附上相关的函数说明,便于大家理解:


m.start() //Returns the start index of the previous match.

m.end()   //Returns the offset after the last character matched.

m.find()  //Attempts to find the next subsequence of the input sequence that matches the pattern



版权声明:本文为zhanghefeng1314原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。