首頁  >  文章  >  後端開發  >  如何使用正規表示式從字串中提取浮點值?

如何使用正規表示式從字串中提取浮點值?

DDD
DDD原創
2024-10-21 12:30:04252瀏覽

How Can Regular Expressions Be Used to Extract Floating-Point Values from Strings?

使用正規表示式從字串中提取浮點值

考慮從字串中提取雙精確值的任務。要使用正規表示式實現此目的,涉及以下步驟:

  1. 構造正規表示式:

    <code class="python">import re
    
    pattr = re.compile(???)
    x = pattr.match("4.5")</code>

  2. <code class="python">re_float = re.compile("""(?x)
    ^
       [+-]?\ *      # an optional sign and space
       (             # integers or f.p. mantissas
           \d+       # start with a ...
           (           # ? takes care of integers
               \.\d* # mantissa a.b or a.
           )?
          |\.\d+     # mantissa .b
       )
       ([eE][+-]?\d+)?  # optionally match an exponent
    $""")</code>
  3. 使用Perl 相容的正規表示式:
  4. Perl 文件中用於擷取浮點值的適當正規表示式是:

    <code class="python">m = re_float.match("4.5")
    print(m.group(0))</code>

    尋找並檢索符合:

    4.5
    要提取雙精確度值,請將已編譯的正規表示式應用於所需的字串:
  5. 這將輸出:

    <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))</code>

    從字串中提取多個值:

    ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2', '       1.01', '-.2', ' 123', ' .123']
    要從較大的字串中提取多個浮點值,請使用findall () 方法:
這將傳回提取值的列表,包括:

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn