关于 r:gsub 并在字符串中返回正确的数字 | 珊瑚贝

gsub and returning the correct number in a string


我在数据框中有一个文本字符串,如下所示

2 Sector. District 1, Area 1

我的目标是提取 Sector 之前的数字,否则返回空白。

我认为以下正则表达式会起作用:

1
gsub(“^(?:([0-9]+).*Sector.*|.*)$”,”\\\\1″,TEXTSTRINGCOLUMN)

当单词 Sector 不存在时,这正确地不返回任何内容,但返回 1 而不是 2。非常感谢有关我哪里出错的帮助。谢谢!


我们可以对”扇区”使用正则表达式前瞻,将数字捕获为一个组,并在替换中指定捕获组 (\\\\1)。

1
2
sub(‘.*?(\\\\d+)\\\\s*(?=Sector).*’, ‘\\\\1’, v1, perl=TRUE)
#[1]”2″

编辑:根据@Avinash Raj 的评论修改。

不使用环视,(感谢@Avinash Raj)

1
sub(‘.*?(\\\\d+)\\\\s*Sector.*’, ‘\\\\1’, v1)

数据

1
v1 <-“2 Sector. District 1, Area 1”
  • 这不适用于 Sector 不存在的情况 – 例如x <- c(“2 Sector. District 1, Area 1″,”Nothing”)
  • @thelatemail str_extract(x, (\\\\d+)(?=\\\\s*Sector)) 为此返回 NA
  • @thelatemail 看起来 OP 的初始代码返回 那些。我不确定 OPs 代码在哪里失败。
  • @akrun wait… 不适用于 23 Sector,您的正则表达式必须是 .*?(\\\\d+)
  • 不,需要 Perl,sub(.*?(\\\\d+)\\\\s*Sector.*, \\\\1, v1) :-)
  • 启用 perl,str_extract(v1, perl(“\\\\d+(?=\\\\s*Sector)”))
  • @AvinashRaj 在新的 stringr 版本中,不需要用 perl package。因为它给了我警告 perl is deprecated. Please use regexp instead


试试吧,

1
2
3
x <-“2 Sector. District 1, Area 1”
substring(x, 0, as.integer(grepl(“Sector”, x)))
#[1]”2″

来源:https://www.codenong.com/32837308/

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?