复杂的正则表达式模式以替换逗号。

huangapple go评论76阅读模式
英文:

Complex RegEx patter for replacing commas

问题

我有一个正则表达式模式的问题,它必须将两个逗号替换为一个逗号,并在后面添加一个空格,但如果只有一个逗号且后面没有空格,我希望它在那里添加一个空格。

目前,我正在使用这个模式 - /([,]+)/g,但在只有一个逗号和后面有空格的情况下,它会再添加一个空格。

案例:

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

(我正在使用Java)

你有什么建议,这个正则表达式模式应该是什么样的?我还有点困惑。

谢谢。

英文:

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.

答案1

得分: 1

你要确保在每个逗号链后面都有一个空格,而不是在每种情况下都创建一个空格。您可以使用前瞻来实现这一点,但我更喜欢包容性检查,即如果字符链已包含空格,则将其替换掉。

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

上面的答案将接受逗号后的所有(真正的)空格,并将它们替换掉,这样,您插入的单个空格就是唯一的。这不适用于换行符。如果有换行符并且想要明确处理它们,那么您需要采用不同的方法。换句话说,如果逗号后面跟着一个换行符,那么在(新的)逗号和换行符之间将有一个空格。

英文:

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.

huangapple
  • 本文由 发表于 2020年8月10日 17:14:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63337324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定