42-*_*42- 8 regex r scientific-notation
我试图回答一个问题(后来被删除),我认为这是在询问提取科学记数法的文本表示.(使用R的regex实现,需要对元字符进行双重转义,并且可以在纯PCRE或Perl模式中使用,我之间的差异我并不真正理解.)我已经解决了大部分任务但仍然似乎无法捕获捕获组中的前导减号.我似乎唯一能让它成功的方法是使用前导的开括号:
> txt <- c("this is some random text (2.22222222e-200)", "other random (3.33333e4)", "yet a third(-1.33333e-40)", 'and a fourth w/o the "e" (2.22222222-200)')
> sub("^(.+\\()([-+]{0,1}[0-9][.][0-9]{1,16}[eE]*[-+]*[0-9]{0,3})(.+$)", "\\2" ,txt)
[1] "2.22222222e-200" "3.33333e4" "-1.33333e-40" "2.22222222-200"
> sub("^(.+\\()([-+]?[0-9][.][0-9]{1,16}[eE]*[-+]*[0-9]{0,3})(.+$)", "\\2" ,txt)
[1] "2.22222222e-200" "3.33333e4" "-1.33333e-40" "2.22222222-200"
#but that seems to be "cheating" ... my failures follow:
> sub("^(.+)([-+]?[0-9][.][0-9]{1,16}[eE]*[-+]*[0-9]{0,3})(.+$)", "\\2" ,txt)
[1] "2.22222222e-200" "3.33333e4" "1.33333e-40" "2.22222222-200"
> sub("^(.+)(-?[0-9][.][0-9]{1,16}[eE]*[-+]*[0-9]{0,3})(.+$)", "\\2" ,txt)
[1] "2.22222222e-200" "3.33333e4" "1.33333e-40" "2.22222222-200"
> sub("^(.+)(-*[0-9][.][0-9]{1,16}[eE]*[-+]*[0-9]{0,3})(.+$)", "\\2" ,txt)
[1] "2.22222222e-200" "3.33333e4" "1.33333e-40" "2.22222222-200"
Run Code Online (Sandbox Code Playgroud)
我用"科学记数法正则表达式减去"之类的术语来搜索我的耐心程度
你可以试试
library(stringr)
unlist(str_extract_all(txt, '-?[0-9.]+e?[-+]?[0-9]*'))
#[1] "2.22222222e-200" "3.33333e4" "-1.33333e-40" "2.22222222-200"
Run Code Online (Sandbox Code Playgroud)
使用基于前导括号后捕获的方法
str_extract(txt, '(?<=\\()[^)]*')
#[1] "2.22222222e-200" "3.33333e4" "-1.33333e-40" "2.22222222-200"
Run Code Online (Sandbox Code Playgroud)