简体   繁体   English

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

[英]String Replacement Regex Condition

I have a text 我有一条短信

Hello everyone, my name is Ke- 大家好,我叫Ke-

vin, I was born in Indonesia 20- vin,我在印尼出生20-

01-1990. 1990年1月1日。 Nice to meet you. 很高兴见到你。

So how can I replace the text to 那么我该如何替换为

Hello everyone, my name is Kevin, I was born in Indonesia 20-01-1990. 大家好,我叫凯文(Kevin),我于1990年1月20日出生在印度尼西亚。 Nice to meet you. 很高兴见到你。

I've tried using String string = string.replace("-\\n" , ""); 我已经尝试过使用String string = string.replace("-\\n" , "");

Hello everyone, my name is Kevin, I was born in Indonesia 2001-1990. 大家好,我叫凯文(Kevin),我于2001-1990年出生于印度尼西亚。 Nice to meet you. 很高兴见到你。

so how to put the different case in replace string? 那么如何将不同的大小写放在替换字符串中呢? between alphabet before "-" and number. 在“-”之前的字母和数字之间。

When the hyphen is preceded by a digit, you could use a capturing group to match the digit and the hyphen, and use $1 as replacement: 当连字符前面有数字时,可以使用捕获组来匹配数字和连字符,并使用$1作为替换:

(?:(\\d-)|-)
  • Captures a digit followed by a hyphen 捕获一个数字,后跟一个连字符
  • Or matches a hyphen (not captured) 或匹配连字符(未捕获)

Code

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+" , "$1");

System.out.println(result);

Output 输出量

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM