![](/img/trans.png)
[英]How to use regular expression to match specific digits and mutate conditionally? (R)
[英]Regular expression in R: How to cut sequence of digits?
有一個小文本列表。 結尾部分的某些文本可能包含由空格分隔的數字序列。 在這種情況下,該序列的第一個數字必須保留在文本中,以截斷其余的數字序列。 怎么做? 例:
將gsub()
與以下模式一起使用:
(\\d+)(?: \\d+)*$
然后替換為第一個捕獲組\\\\1
。
x1 <- "Some words"
x2 <- "Some words 544 11"
x3 <- "Some 1 words 3 33 444"
result1 <- gsub("(\\d+)(?: \\d+)*$", "\\1", x1)
result2 <- gsub("(\\d+)(?: \\d+)*$", "\\1", x2)
result3 <- gsub("(\\d+)(?: \\d+)*$", "\\1", x3)
print(result1)
print(result2)
print(result3)
演示在這里:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.