Use gsub remove all string before first numeric character

前端 未结 2 1538
小鲜肉
小鲜肉 2021-01-12 17:06

Use gsub remove all string before first white space in R

In this example, we try to remove everything before a space with sub(\".*? (.+)\", \"\\\\1\", D$name)<

2条回答
  •  借酒劲吻你
    2021-01-12 17:22

    You may use

    > x <- c("lala65lolo","papa3hihi","george365meumeu")
    > sub("^\\D+", "", x)
    [1] "65lolo"    "3hihi"     "365meumeu"
    

    Or, to make sure there is a digit:

    sub("^\\D+(\\d)", "\\1", x)
    

    The pattern matches

    • ^ - start of string
    • \\D+ - one or more chars other than digit
    • (\\d) - Capturing group 1: a digit (the \1 in the replacement pattern restores the digit captured in this group).

    In a similar way, you may achieve the following:

    • sub("^\\s+", "", x) - remove all text up to the first non-whitespace char
    • sub("^\\W+", "", x) - remove all text up to the first word char
    • sub("^[^-]+", "", x) - remove all text up to the first hyphen (if there is any), etc.

提交回复
热议问题