简体   繁体   English

使用正则表达式在字符串之间添加空格

[英]Add spaces between string using regular expression

I am learning regular expression,hence asking this question. 我正在学习正则表达式,因此问这个问题。 I have a string 我有一个弦

String time=7AM-9PM; 字符串时间= 7 AM-9PM;

I need to add spaces so that the string would come out like this 我需要添加空格,以便字符串像这样出来

time=7 AM - 9 PM. 时间= 7 AM-9 PM。

I have tried so far the following regular expression 到目前为止,我已经尝试了以下正则表达式

time.replaceAll("(\\d{1})", "$1 "); time.replaceAll(“(\\ d {1})”,“ $ 1”);

and it is giving output 它正在输出

9 AM-7 PM 上午9点至下午7点

Now I just need the space before and after -. 现在我只需要-之前和之后的空间。 Can someone suggest what else I need to add in the regex to achieve the final output. 有人可以建议我需要在正则表达式中添加其他内容以实现最终输出。

Thank You 谢谢

If you tried 7AM-10PM you'd find that 10 would be split up like 1 0 : presumably not what you want! 如果您尝试7AM-10PM您会发现10会像1 0一样分裂:大概不是您想要的!

I managed to do it with 2 replaceAlls: 我设法做到了2个replaceAlls:

String time = "7AM-10PM"
System.out.println(time
  .replaceAll("([0-9]+)", "$1 ")   //spaces around numbers
  .replaceAll("([\\-])", " $1 ")); //spaces around '-'

result : 7 AM - 10 PM 结果: 7 AM - 10 PM

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

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