San*_*osh 2 regex r regex-lookarounds
我正在尝试识别 R 中某个子字符串之后出现的数字。
例如:
sa <- "100 dollars 200"
Run Code Online (Sandbox Code Playgroud)
在上面的字符串中,为了查找单词 后面出现的数字dollar,我执行以下代码:
str_match_all(sa,"(?<=dollars )\\d+")
Run Code Online (Sandbox Code Playgroud)
我得到以下结果:
[[1]]
[,1]
[1,] "200"
Run Code Online (Sandbox Code Playgroud)
但是,当我使用以下输入时:
sa <- "100 dollars for 200 pesos"
Run Code Online (Sandbox Code Playgroud)
我非常无法获得输出200。
另一种方法是简单地使用gsub()来获取您想要的号码。更具体地说,您可以定义一个模式来搜索单词“dollars”后面的第一个数字。
# define the pattern
pat <- "^.*dollars.*?([0-9]+).*"
# example 1
str <- "100 dollars for 200 pesos"
gsub(pat, "\\1", str)
[1] "200"
# example 2
str <- " 100, actually 100.12 dollars for 200 pesos or 1000 dimes"
gsub(pat, "\\1", str)
[1] "200"
Run Code Online (Sandbox Code Playgroud)
为了更好地解释该模式:
^ >> from the beginning of the string...
.* >> every character till...
dollars >> the substring 'dollars'...
.*? >> and than any character until the first...
([0-9]+) >> number of any length, that is selected as group...
.* >> and then everything else
Run Code Online (Sandbox Code Playgroud)
当此模式匹配时,gsub()将其替换为选择为组的数字,即“dollars”之后的第一个数字。