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:
- 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. - Partial matches on decimal amounts: For values like
$70.00, the regex matches$7(since the next character is0, not a dot), replaces it with$7.00, and leaves the remaining0.00intact—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
.00added. - Already-formatted decimal amounts stay unchanged.
内容的提问来源于stack exchange,提问作者semisolidwhale
相关产品推荐
相关产品推荐

