字符串替换正则表达式条件

String Replacement Regex Condition

我有一条短信

Hello everyone, my name is Ke-

vin, I was born in Indonesia 20-

01-1990. Nice to meet you.

那么如何将文本替换为

Hello everyone, my name is Kevin, I was born in Indonesia 20-01-1990. Nice to meet you.

我试过使用 String string = string.replace("-\n" , "");

Hello everyone, my name is Kevin, I was born in Indonesia 2001-1990. Nice to meet you.

那么如何在替换字符串中放入不同的大小写呢?在“-”之前的字母和数字之间。

当连字符前面有数字时,您可以使用 capturing group 来匹配数字和连字符,并使用 </code> 替换:</p> <pre><code>(?:(\d-)|-)

  • 捕获一个数字后跟一个连字符
  • 或匹配连字符(未捕获)

代码

String string = "Hello everyone, my name is Ke-\nvin, I was born in Indonesia 20-\n01-1990. Nice to meet you.";
String result = string.replaceAll("(?:(\d-)|-)\n+" , "");

System.out.println(result);

输出

Hello everyone, my name is Kevin, I was born in Indonesia 20-01-1990. Nice to meet you.

字符串结果 = string.replaceAll("-","").replaceAll("\r\n", "");