【问题标题】:Regex Question: separate string at the last comma in string正则表达式问题:在字符串的最后一个逗号处分隔字符串
【发布时间】:2021-10-12 02:40:45
【问题描述】:

我的字符串模式如下:

1233 fox street, omaha NE ,69131-7233
Jeffrey Jones, 666 Church Street, Omaha NE ,69131-72339
Betty Davis, LLC, 334 Aloha Blvd., Fort Collins CO ,84444-00333
,1233 Decker 街, 奥马哈 NE ,69131-7233

我需要把上面的字符串分成四个变量:nameaddresscity_statezipcode

由于该模式有三到四个逗号,我从右边开始将字段分隔为多个字段。

rubular.com 表示模式 ("(,\\d.........)$"))) 或模式 ",\d.........$" 将匹配字符串末尾的邮政编码。

regex101.com,发现以上两种模式都不匹配。

当我尝试分开时:

#need to load pkg:tidyr for the `separate`

功能 图书馆(tidyr) 分开(street_add, c("street_add2", "zip", sep= ("(,\d.........)$"))))

或与:

separate(street_add, c("street_add2", "zip", sep=  (",\d.........$"))) 

在这两种情况下,R 在字符串中的第一个逗号处拆分。
如何将字符串分割成段?
谢谢。

【问题讨论】:

  • Re: 引用rubular.com ...您应该意识到,R 中正则表达式的语法与其他一些语言不同。也许 Ruby 和 R 有同样的怪癖(我不知道是不是这样),但如果是这样,你应该这么说。否则,您应该依赖 R 特定的权限,例如 R-regex 模式的代码。

标签: r regex


【解决方案1】:

使用

sep=",(?=[^,]*$)"

regex proof

解释

--------------------------------------------------------------------------------
  ,                        ','
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    [^,]*                    any character except: ',' (0 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    $                        before an optional \n, and the end of
                             the string
--------------------------------------------------------------------------------
  )                        end of look-ahead

【讨论】:

  • Ryszard:谢谢你的代码和解释。 :)
  • 谢谢Ryszard。我仍然在这里学习。
  • 该网站只有在用户明白 R 需要修改转义序列时才有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多