我有一个包含页面路径的数据框列:
pagePath
/text/other_text/123-some_other_txet-4571/text.html
/text/other_text/another_txet/15-some_other_txet.html
/text/other_text/25189-some_other_txet/45112-text.html
/text/other_text/text/text/5418874-some_other_txet.html
/text/other_text/text/text/some_other_txet-4157/text.html
我想要做的是提取
/
之后的第一个数字,例如 123
从每一行。为了解决这个问题,我尝试了以下方法:
num = gsub("\\D"," ", mydata$pagePath) /*to delete all characters other than digits */
num1 = gsub("\\s+"," ",num) /*to let only one space between numbers*/
num2 = gsub("^\\s","",num1) /*to delete the first space in my string*/
my_number = gsub( " .*$", "", num2 ) /*to select the first number on my string*/
我以为这是我想要的,但我遇到了一些麻烦,尤其是像示例中的最后一行这样的行:
/text/other_text/text/text/some_other_txet-4157/text.html
所以,我真正想要的是提取
/
之后的第一个数字.任何帮助将非常受欢迎。
最佳答案
您可以将以下正则表达式与 gsub
一起使用:
"^(?:.*?/(\\d+))?.*$"
并替换为
"\\1"
.见 regex demo .代码:
> s <- c("/text/other_text/123-some_other_txet-4571/text.html", "/text/other_text/another_txet/15-some_other_txet.html", "/text/other_text/25189-some_other_txet/45112-text.html", "/text/other_text/text/text/5418874-some_other_txet.html", "/text/other_text/text/text/some_other_txet-4157/text.html")
> gsub("^(?:.*?/(\\d+))?.*$", "\\1", s, perl=T)
[1] "123" "15" "25189" "5418874" ""
正则表达式将可选地(使用
(?:.*?/(\\d+))?
子模式)匹配从开头到第一个 /
的字符串的一部分。 (使用 .*?/
)后跟 1 个或多个数字(将数字捕获到第 1 组,使用 (\\d+)
),然后是字符串的其余部分(使用 .*$
)。请注意
perl=T
是必须的。带纵梁
str_extract
,您的代码和模式可以缩短为:> str_extract(s, "(?<=/)\\d+")
[1] "123" "15" "25189" "5418874" NA
>
str_extract
如果前面有 /
,将提取前 1 位或更多位数字。 (/
本身不会作为匹配的一部分返回,因为它是后视子模式,零宽度断言,不会将匹配的文本放入结果中)。
关于regex - R正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35936715/