我曾试图回答一个问题(后来被删除了),我认为这个问题是关于提取科学计数法文本表示的。 (使用R的正则表达式实现需要对元字符进行双重转义,可以在纯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"
我已经用诸如“科学计数法正则表达式减号”等术语耐心地在SO上搜索了很长时间。
str_extract_all
函数,似乎可以通过unlist(str_extract_all(txt, '-?[0-9.]+e?[-+]?[0-9]*'))
实现。 - akrunabs()
反身进行比较,并根据该比较来分离负数。 - baptiste