`

java正则针对同一行出现\r\n的替换

阅读更多

 

 

工作中,在解析Mongo数时,会出现mongo数据字符串自带 \r\n的数据,在etl到hive中,这种数据又不能变成多行,否则数据列对不上,因此需要处理, 目前使用的做法是 正则表达式:

 

package com.xuele.bigdata.xetl.mongo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*System.out.println(1);
		System.out.println(IOUtils.LINE_SEPARATOR);
		System.out.println(2);*/
		String json = "hello\r\nworld welcome to newland" ;
		StringBuilder sb = new StringBuilder("");
		Matcher m = Pattern.compile("(?m)^.*$").matcher(json);  // (?m) 在这种模式下,'^'和'$'分别匹配一行的开始和结束  表示匹配整行 
        while (m.find()) {
            //System.out.println("line = " + m.group());
        	System.out.println(m.group());  
        	/**这次的结果
        	 * hello
			   world welcome to newland
        	 */
            sb.append(m.group()).append(" ");  
        }
        System.out.println(sb.toString()); //  hello world welcome to newland 
        
	}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics