You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R正则:为字符串末尾可变长度的美元金额补全小数位

Fixing Regex for Adding Decimal Places to Dollar Amounts

Let's break down what's going wrong with your current regex and fix it step by step.

Issues with Your Current Code

Your regex "(\\$[0-9]+)([^\\.])" has two key problems:

  1. Requires a trailing non-decimal character: The ([^\\.]) group means the dollar amount must be followed by something that's not a dot. This fails for amounts at the end of the string (like $30), since there's no trailing character to match.
  2. Partial matches on decimal amounts: For values like $70.00, the regex matches $7 (since the next character is 0, not a dot), replaces it with $7.00, and leaves the remaining 0.00 intact—resulting in the broken $7.000.00.

Solution: Use a Negative Lookahead

Instead of checking for a trailing non-dot character, use a negative lookahead to ensure the number isn't followed by a decimal point. This way, we only target dollar amounts that don't already have decimals, whether they're in the middle or end of the string.

Here's the corrected code:

library(tibble)

ex <- tibble(strings = c("10/$20/$30", "$40/50/60", "$70.00/80/$90.00"))
gsub("\\$([0-9]+)(?!\\.)", "$\\1.00", ex$strings, perl = TRUE)

How This Works:

  • \\$([0-9]+): Matches a dollar sign followed by one or more digits, capturing the digits in group 1.
  • (?!\\.): A negative lookahead that ensures the digits are not immediately followed by a decimal point. This skips amounts that already have decimals (like $70.00).
  • perl = TRUE: Required in R to enable lookahead assertions.

Result:

[1] "10/$20.00/$30.00" "$40.00/50/60"      "$70.00/80/$90.00"

This gives exactly what you expected:

  • Non-decimal dollar amounts (including those at the end of the string) get .00 added.
  • Already-formatted decimal amounts stay unchanged.

内容的提问来源于stack exchange,提问作者semisolidwhale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:52:49