regex - R正则表达式问题

标签 regex r

我有一个包含页面路径的数据框列:

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/

相关文章:

R - 模糊查找和重新编码

在 R 中使用 ifelse 替换值

javascript - 货币字段的正则表达式

regex - 检查网址是否为有效的 Google 搜索网址

php - 使用正则表达式从文本中删除 URL(当前域除外)

R将大型CSV文件转换为HDFS

r - 使用 gsub 在字符串中仅保留字母数字字符和空格

r - igraph layout.fruchterman.reingold 离群值(包含示例图像)

javascript - JavaScript 中的正则表达式。只允许字母、逗号和标点符号

java - 用于从字符串中查找 http 和 https url 的正则表达式