简体   繁体   中英

Complex RegEx patter for replacing commas

I have a problem with the REGEX pattern, which has to replace two commas with one comma with a space behind, but if there is only one comma and there is no space behind it, I want it to add that space there.

Currently, I am using this pattern - /([,]+)/g , but in case when I have one comma and space behing, it adds one more space behing.

Cases:

  • text,,text -> text, text
  • text, text -> text, text
  • text,text -> text, text
  • text,,text,,text -> text, text, text

(I am using Java)

Do you have any suggestions, how this REGEX pattern should look like? I am still bit confused.

Thanks.

What you want is to ensure a space behind every comma-chain, not create one in every case. You can either do this with lookahead, but I prefer the inclusive check, if the character chain already contains spaces, and if so, replace them as well.

str.replaceAll("\\,+ *", ", ");

The above answer will take all (real) spaces after the comma(s) and just replace them as well, this way, the single space that you insert is the only one. This will NOT work for line breaks. If you have line breaks and want to handle them explicitly, then you need to proceed differently. In other words, if the comma(s) is/are followed by a line break, you will have a white space between the (new) comma and line break.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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