在某个单词后提取数字

时间:2016-06-30 10:37:28

标签: regex r

我正在尝试构建一个正则表达式,以便在某个字符串后提取一个6位数字(正数或负数),即' LogL ='。

它来自某些软件的文本输出。

   7 LogL=-3695.47     S2=  9.0808       1891 df    2.263     0.2565    
   9 LogL= 2456.30     S2=  1.2789       1785 df    1.244     0.1354    

我在R中尝试了以下内容:

txt <- "   9 LogL= 2456.30     S2=  1.2789       1785 df    1.244     0.1354   "
as.numeric(unlist(strsplit(sub(".*LogL=*", "", txt), " "))[1])

不适用于正数。而且我想象它的粗暴/丑陋的方式。 我试着干预regex101.com

尝试了与Stackoverflow相关的问题:(1) (2) (3)

我有点迷茫,似乎无法理解正则表达式。我相信这是小菜一碟。帮助

4 个答案:

答案 0 :(得分:5)

我使用look-behind regex

txt <- "   7 LogL=-3695.47     S2=  9.0808       1891 df    2.263     0.2565    
           9 LogL= 2456.30     S2=  1.2789       1785 df    1.244     0.1354   "
pattern <- "(?<=LogL\\=)\\s*\\-*[0-9.]+"
m <- gregexpr(pattern, txt, perl = TRUE)
as.numeric(unlist(regmatches(txt, m)))
#1] -3695.47  2456.30

答案 1 :(得分:4)

尝试

//This is the Click

public void ClickRibbon(Office.IRibbonControl control){

     //After this, we have to read a next Click anywhere on the Form whose coordinates needs to be determined
}

它匹配您的文本(LogL),一个等号,后跟任意数量的空格。然后它捕获:

  • 可选LogL=\s*(-?\d+(?:\.\d+)?)
  • 位数,至少一个
  • 并且可选地,-后跟至少一位数。

Check it here at regex101

答案 2 :(得分:3)

如果您对非正则表达式替代感兴趣:

library(stringr)
txt <- "   9 LogL= 2456.30     S2=  1.2789       1785 df    1.244     0.1354   "
word(txt, 2, sep = "=") %>% word(2, sep = " ")

它适用于正数和负数。

答案 3 :(得分:2)

我们可以使用str_extract

 library(stringr)
 as.numeric(str_extract_all(txt, "(?<=LogL=\\s{0,1})[-0-9.]+")[[1]])
 #[1] -3695.47  2456.30

或者我们可以使用strsplitgsub

的组合
as.numeric(gsub(".*LogL=\\s*|\\s+.*", "", trimws(strsplit(txt, "\n")[[1]])))
#[1] -3695.47  2456.30
相关问题