r - 不要在句末包含 gsub 句号
问题描述
我正在尝试在 R 中做一个 gsub 以用箭头替换所有数字(例如:$1.48、1,765、87)。(<>,<<1,765>>,<<87>>)
这是我当前的 gsub:
text<-c("数字示例是一和二、3、1,284 和五十九。", "这个冰棒售价 1.48 美元。")
subbedNum<-gsub("\\b([$0-9.,]+)\\b", "<<\\1>>", text)
然而,它的结果是在句尾的句号周围也放置了箭头,并且箭头中没有 $:
[1] "My favorite numbers are <<8>>, <<3,289>> and <<4>><<.>>"
[2] "This book costs $<<1.48.>>"
预期输出是:
[1,]"My favorite numbers are <<8>>, <<3,289>> and <<4>>."
[2,] "This book costs <<$1.48>>."
我怎样才能改变这个?
解决方案
代替单词边界(可能有一些边缘情况),我们可以捕获任何非数字之后的数字,后跟一个点或逗号,以及一个或多个数字。在替换中,使用捕获组的反向引用并将其格式化为<<>>
gsub("[^$0-9.,]([$0-9]+([.,][0-9]+)?)\\b", "<<\\1>>", text)
#[1] "Examples of numbers are one and two,<<3>>,<<1,284>> and fifty nine."
#[2] "This ice pop costs<<$1.48>>."
数据
text<-c( "Examples of numbers are one and two, 3, 1,284 and fifty nine.", "This ice pop costs $1.48.")
推荐阅读
- vue.js - 如何减小v-switch的宽度
- python - python pandas excel
- android - 如何在android的mp图表中每小时添加条并对齐每个顶部标签
- python - 如何将火炬张量转换为浮点数?
- sql - Oracle Apex - 用线条或颜色分隔卡片文本行
- angular - 保存 mat-stepper 状态并在页面刷新时将其传递给相同的 mat-stepper
- mysql - MySQL SELECT 在 SELECT 子句或 WHERE 子句中,以便进一步过滤
- node.js - UnhandledPromiseRejectionWarning: TypeError: questionList is not iterable
- r - trycatch 在 R 中只返回警告而不是错误
- sql - 只取行集中的第一行