Java和Regex添加一些换行符

时间:2013-12-15 00:10:23

标签: java regex

所以我有以下字符串,我想在数字

之前插入一些\ n
1. Hello 2. Satuday 3.Kidding 4. sdsfjdfkj

我想替换它看起来像这样

1. Hello
2. Satuday
3.Kidding
4. sdsfjdfkj

我在想这样的事情

variable.replaceAll("\d.", "\n");

我不确定如何获得替代

的上下文

3 个答案:

答案 0 :(得分:2)

您可以将replaceAll与非捕获正则表达式一起使用,如下所示:

String res = str.replaceAll("\\b(?=\\d+[.])", "\n");

将字符串作为输入,打印

1. Hello 
2. Satuday 
3.Kidding 
4. sdsfjdfkj

Demo on ideone.

答案 1 :(得分:1)

所以基本上你想用新行替换后面有数字和点的每个空格。尝试

variable = variable.replaceAll("\\s+(\\d+[.])", "\n$1"); 
// $1 is reference to captured group 1 which will contain number and dot

variable = variable.replaceAll("\\s+(?=\\d+[.])", "\n");
// (?=...) is called look-ahead, \\s+(?=\\d+[.]) makes sure that after matched 
// whitespace there will be number and dot

答案 2 :(得分:0)

有点慢,但很容易解决:

string=string.replace("1","\n1");//  '\n' is the escape sequence for newline

然后重复所有数字