提取某个单词后的数字 [英] Extract number after a certain word

查看:36
本文介绍了提取某个单词后的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个正则表达式来提取某个字符串后的 6 位数字(正数或负数),即LogL=".

I am trying to build a regex expression to extract a 6 digit number (positive or negative) after a certain string, namely 'LogL='.

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

It comes from text output from certain software.

   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 中尝试了以下内容:

I tried the following in 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

Doesn't work for positive numbers. And I imagine its very crude/ugly way of going about it. I tried meddling on regex101.com

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

Stackoverflow related questions tried: (1) (2) (3)

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

I am kind of lost and can't seem to understand regex expressions. I am sure this is a piece of cake. Help?

推荐答案

我会使用 look-在正则表达式后面:

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

这篇关于提取某个单词后的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆