如何使用文本中的正则表达式选择浮点数或整数

问题描述 投票:1回答:3

我想从某些文本中匹配给定的整数或浮点数,但要限制在特定的行上,因为相似的数字可能出现在不同的位置。

这是我输入的内容,数字组成的,不要试图将“总计”与“部分”相关联:

===> Verifying dependencies...
===> Compiling sample
===> Performing cover analysis...
  |------------------------|------------|
  |                module  |  coverage  |
  |------------------------|------------|
  |            sample_app  |    12.94%  |
  |            sample_sup  |    56.78%  |
  |                sample  |       96%  |
  |------------------------|------------|
  |                 total  |    23.02%  |
  |------------------------|------------|
  coverage calculated from:
    /tmp/workspace/_build/test/cover/ct.coverdata
    /tmp/workspace/_build/test/cover/eunit.coverdata
  cover summary written to: /tmp/workspace/_build/test/cover/index.html

我要提取 23.02,因此它是带有total的行中的数字。这是我到目前为止的正则表达式:

^.+total.+(\d+|\d+\.\d+)%.+$

但是效果不好,它只匹配该行的最后一位。

我正在测试Rubular上的图案。

regex ruby
3个回答
2
投票

您有两个问题。首先是.+是贪婪的,这意味着,如果用于从文件中搜索一行,它将吞入尽可能多的字符(换行符除外),但仍确保匹配,这意味着匹配最后一个数字。

[第二个问题是,如果您将文件读入字符串并搜索字符串,则.*将不会超过第一行,因为它将不匹配换行符。通过添加多行修饰符(/m)可以轻松解决该问题,该修饰符指示.*匹配所有字符,包括换行符。

如果将文件读入字符串,则可以使用以下正则表达式从字符串中提取感兴趣的字符。

r = /
    ^          # match beginning of line
    [ ]*       # match 0+ spaces
    \|         # match a toothpick
    [ ]+       # match 1+ spaces
    total      # match 'total'   
    [ ]+       # match 1+ spaces
    \|         # match a toothpick
    [ ]+       # match 1+ spaces
    \K         # forget everything matched so far
    \d+        # match a digit
    (?:\.\d+)  # match '.' then 1+ digits in non-capture group
    ?          # optionally match the non-capture group
    (?=        # begin a positive lookahead
      %        # match '%'
      [ ]+     # match '%' then 1+ spaces
      \|[ ]*   # match a toothpick then 0+ spaces
      $        # match end-of-line
    )          # end positive lookahead
    /x         # free-spacing mode

我已经以自由间距模式1]编写了正则表达式,以使其具有自记录功能。通常按如下方式编写。

/^ *\| +total +\| +\K\d+(?:\.\d+)?(?=% +\| *$)/

假设您将文件读入变量str所保存的字符串中:

str =<<~END
===> Verifying dependencies...
===> Compiling sample
===> Performing cover analysis...
  |------------------------|------------|
  |                module  |  coverage  |
  |------------------------|------------|
  |            sample_app  |    12.94%  |
  |            sample_sup  |    56.78%  |
  |                sample  |       96%  |
  |------------------------|------------|
  |                 total  |    23.02%  |
  |------------------------|------------|
  coverage calculated from:
    /tmp/workspace/_build/test/cover/ct.coverdata
    /tmp/workspace/_build/test/cover/eunit.coverdata
  cover summary written to: /tmp/workspace/_build/test/cover/index.html
END

然后

str[r] #=> "23.02" 

1在自由空间模式下,在解析正则表达式之前将所有空格删除,这就是为什么必须保护属于正则表达式的空格的原因。我已经通过将每个空格放在字符类中来做到这一点,但是可以转义它们,也可以使用\s(如果适用)。


1
投票

我想保持简单,将使用此:


0
投票

您可以执行以下操作:

© www.soinside.com 2019 - 2024. All rights reserved.