java split多个字符串分割_java split用多个标点拆分,并保留分隔符

String[] split(String regex)

根据给定的正则表达式的匹配来拆分此字符串。

注意:竖线"|" 要转义写成 "\\|",还有一些其他的特殊字符是需要转义的 如 \\. \\? 等

1.用多个标点拆分

strs = str.split("[、,。;?!,.;?!]");

strs = str.split("、|,|。|;|?|!|,|\\.|;|\\?|!|]");

2.还想保留分隔符,

笨方法:在要拆分的标点后边加一个新的拆分符,用新的拆分符拆分

//这么替换,是为了拆分后,还能保存标点符号,//可再优化

line = line.replaceAll("、", "、|");

line = line.replaceAll(",", ",|");

line = line.replaceAll("。", "。|");

line = line.replaceAll(";", ";|");

line = line.replaceAll("?", "?|");

line = line.replaceAll("!", "!|");

line = line.replaceAll(",", ",|");

line = line.replaceAll("\\.", ".|");

line = line.replaceAll(";", ";|");

line = line.replaceAll("\\?", "?|");

line = line.replaceAll("!", "!|");

strs = line.split("\\|");

3.还想单独保留分隔符,

自己写了个方法,仅供参考:

用StringBuilder,一个一个字符的去拼。

phrase = new Phrase(str,String.valueOf(ch),l+1,++no);

Phrase 是自定义类,第一个参数是短句,第二个参数是分隔符

reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),encoding)); //考虑到编码格式

String line;

StringBuilder sb;

//int num = 0; //总句码

int l=0; //行序号

while((line = reader.readLine()) != null){

//line = new String(line.getBytes("ISO-8859-1"),"UTF-8");

//System.out.println(line);

//line = line.replaceAll("[,。;?!,.;?!]", "|");

line = line.replaceAll("| ", "");

sb = new StringBuilder();

String str="";

//String punctuation = "";

//line = ",abcdev,";//abcdev,asdfasdf.asfejfl;3f23f!;efefef";

char[] chars = line.toCharArray();

int no = 0;

for(char ch : chars){

if(ch == 65279){ //'' //'' //65279 utf-8 bom

continue;

}

if("、,。;?!,.;?!".indexOf(ch) == -1){

sb.append(ch);

} else {

//System.out.println(sb.toString()+ch);

str = sb.toString();

if(str.length()>0){

phrase = new Phrase(str,String.valueOf(ch),l+1,++no);

phraseList.add(phrase);

}

sb = new StringBuilder();

}

}

//后边的没标点的短句

str = sb.toString();

if(str.length()>0){

//System.out.println(str);

phrase = new Phrase(str,"",l+1,++no);

phraseList.add(phrase);

}

l++;

}

reader.close();

别人的解决方法

/*需要分割的文章*/

String str = "第一句。第二句!第三句:第四句;第五句。";

/*正则表达式:句子结束符*/

String regEx=":|。|!|;";

Pattern p =Pattern.compile(regEx);

Matcher m = p.matcher(str);

/*按照句子结束符分割句子*/

String[] words = p.split(str);

/*将句子结束符连接到相应的句子后*/

if(words.length > 0)

{

int count = 0;

while(count < words.length)

{

if(m.find())

{

words[count] += m.group();

}

count++;

}

}

/*输出结果*/

for(int index = 0; index < words.length; index++)

{

String word = words[index];

System.out.println("word = " + word);

}

其他的:

替换中英文空格为空

line = line.replaceAll("| ", "");

替换回车换行为空,注意中间写的是或,因为有的只有一个,有的顺序不同

line = line.replaceAll("\n|\r", "");

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值