我很确定我要找的是R中的正则表达式,用于阅读科学概念。下面是我所做的工作和细节。我非常感谢大家的帮助。
我有一个文本文件,其中有些数字是科学记数法,有些只是小数或整数。我正在尝试使用正则表达式将它们读取到R中。我写了一个程序来做到这一点,只要这些数字不使用科学记数法或负数,我就成功了。
我写的程序是
getBig <-function(fileName,rows,columns)
{
dat <-readChar(fileName, file.info(fileName)$size)
gregexpr('[0-9][/.0-9]+',dat,perl = TRUE)
s <- regmatches(dat,m)
s <- s[[1]]
s<-s[-1] #the first element is the list size
S <- matrix(s,ncol=rows,nrow=columns)
S<- t(S)
return(S)
}我尝试通过使用下面的正则表达式修改上面的程序来修改正则表达式,以包含负数和科学记数法,但没有成功。有谁知道我哪里出问题了吗?感谢任何帮助,我也有下面的示例文件格式。
m <- gregexpr(' [-+]?[0-9]*(/.?[0-9]*([eE][-+]?[0-9]?))?',dat,perl = TRUE)-+?+或-可选
0-9*一个数字0-9最多0次
(启动非可选块/。?最优0-9*匹配0次或更多次
(开始另一个块eE?E或E+或-可选的0-9*数字0-9 1次或更多次)?)?关闭与可选匹配的块
下面的文件格式为行、列
其中(rowN,rowN,rowN)表示第N行的第1-3列。i.e
[3,1] ((1,1,-1),-2.542611418857958448210085379141884323299379672715620518130686999531487002844642281770330354890802745e-05,8.586192002176000052697976968885158408090751670240233300961472896241959822732337130019333683974778635e-05))发布于 2021-06-20 07:31:46
基于Regex for numbers on scientific notation?,以下代码可以在R中运行:
正则表达式仅用于科学记数法:
only_sci_notation_numbers_regex <- "^(-?[0-9]*)\\.?[0-9]+[eE]?[-\\+]?[0-9]+$"用于科学记数法和非科学记数法的正则表达式小数或整数:
all_numbers_regex <- "^(-?[0-9]*)((\\.?[0-9]+[eE]?[-\\+]?[0-9]+)|(\\.[0-9]+))*$"此匹配和不匹配的一些模式的示例:
examples_match <- c(
"0", "1", "1.5", "0.2", "-0", "-1", "-1.5", "-0.2", ".1", "-.1",
"1.05E+10", "1.05e+10","-1.05E+10", "-1.05e+10", "1.05E-10", "1.05e-10","-1.05E-10", "-1.05e-10",
".1e5", ".1E5", "-.1e5", "-.1E5")
examples_not_match <- c("1.", "1.e5", "1e5.")
# matches only numbers in scientific notation (so not examples 1-10)
lapply(examples_match, function(x) grepl(only_sci_notation_numbers_regex, x))
# matches numbers in scientific and non-scientific notation
lapply(examples_match, function(x) grepl(all_numbers_regex, x))
# doesn't match mis-formatted numbers
lapply(examples_not_match, function(x) grepl(only_sci_notation_numbers_regex, x))
lapply(examples_not_match, function(x) grepl(all_numbers_regex, x))这些正则表达式假设完整的字符串代表您的数字。如果您希望匹配一个只构成字符串一部分的科学/非科学数字(例如,要通过stringr::str_extract从较长的字符串中提取它),则必须删除相应表达式开头的^和结尾的$。
https://stackoverflow.com/questions/33084563
复制相似问题