用正则表达式给字符串添加空格

自然语言处理有一种ROUGE的评测方法,使用这种评测方法时有时需要将带评测文本每个汉字之间用空格分开。

原版说明如下:

The recommended ROUGE metrics are Recall and F scores of
Character-based ROUGE-1, ROUGE-2 and ROUGE-SU4. Characterbased
evaluation means that we do not need to perform Chinese word
segmentation when running the ROUGE toolkit. (too long no look:D)Instead, we only need to
separate each Chinese character by using a blank space.

使用正则表达式有一种非常便捷的方法可以解决这个问题:

replaceAll("(.{1})","$1 ")

其中.{1}表示任意一个字符,()表示一组,$1表示第一组

因此字符串ABCDEF匹配过程就是将ABCDEF的每一个字符.{1}都替换成每一个字符.{1}+空格。即是A B C D E F。

拓展:

String str = "abcdefghijklmn";
String str_next = str.replaceAll("(.{1})(.{2})(.{1})","$2$3");

结果是什么呢?

abcdefghijklmn
机智的你一定已经知道答案了吧:bcdfghjklmn~~~~

(.{1})(.{2})(.{1})对应a、bc、d; e、fg、h; i、jk、l;
$2对应bc; fg; jk;
$3对应d; h; l;
 
 
原文地址:https://www.cnblogs.com/kuqs/p/6183426.html