如何使用正規表示式從字串中提取雙精度值?

Mary-Kate Olsen
發布: 2024-10-21 13:00:30
原創
251 人瀏覽過

How to Extract Double Values from Strings Using Regular Expressions?

使用正規表示式從字串中擷取雙精確度值

問題:如何使用正規表示式從字串中分離出雙精度值正規表示式?

考慮以下程式碼片段:

<code class="python">import re

pattr = re.compile(???)    
x = pattr.match("4.5")</code>
登入後複製

解:

使用正規從字串中擷取雙精確值表達式,您可以使用以下正規表示式:

(?x)
   ^
      [+-]?\ *      # Optional sign and space
      (             # Integers or f.p. mantissas:
          \d+       # Integers of the form a...
          (
              \.\d* # Mantissa of the form a.b or a.
          )?        # ? takes care of integers of the form a
         |\.\d+     # Mantissa of the form .b
      )
      ([eE][+-]?\d+)?  # Optionally match an exponent
   $
登入後複製

此正規表示式匹配以可選符號和空格開頭,後跟整數或浮點尾數以及可選指數的字串。

這是一個範例:

<code class="python">import re

re_float = re.compile("""(?x)
   ^
      [+-]?\ *      # Optional sign and space
      (             # Integers or f.p. mantissas:
          \d+       # Integers of the form a...
          (
              \.\d* # Mantissa of the form a.b or a.
          )?        # ? takes care of integers of the form a
         |\.\d+     # Mantissa of the form .b
      )
      ([eE][+-]?\d+)?  # Optionally match an exponent
   $""")

m = re_float.match("4.5")
print(m.group(0))
# -> 4.5</code>
登入後複製

從字串中提取多個數字:

如果您需要從較大的字串中提取多個數字,您可以使用findall() 函數:

<code class="python">s = """4.5 abc -4.5 abc - 4.5 abc + .1e10 abc . abc 1.01e-2 abc
       1.01e-.2 abc 123 abc .123"""
print(re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", s))
# -> ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2',
#     '       1.01', '-.2', ' 123', ' .123']</code>
登入後複製

此正則表達式將匹配由可選符號、空格、整數和可選小數部分的組合以及可選指數表示法組成的任何數字。

以上是如何使用正規表示式從字串中提取雙精度值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!