簡體   English   中英

正則表達式匹配字符串中的數字但不匹配百分比

[英]Regular expression that matches number in string but not percentages

我需要知道是否有一個正則表達式來測試字符串中數字的存在:

  • 匹配Lorem 20 Ipsum
  • 匹配Lorem 2,5 Ipsum
  • 匹配Lorem 20.5 Ipsum
  • Lorem 2% Ipsum 匹配
  • 符合Lorem 20.5% Ipsum
  • 符合Lorem 20,5% Ipsum
  • 符合Lorem 2 percent Ipsum
  • 符合Lorem 20.5 percent Ipsum
  • 符合Lorem 20,5 percent Ipsum
  • 匹配Lorem 20 Ipsum 2% dolor
  • 比賽Lorem 2,5 Ipsum 20.5% dolor
  • 匹配Lorem 20.5 Ipsum 20,5% dolor

也就是說,一個正則表達式可以告訴我字符串中是否有一個或多個數字,但不是百分比值。

我試過的東西作為/[0-9\\.,]+[^%]/ ,但這似乎不工作,我想是因為數字則不是一個百分比符號匹配也是20中的字符串20% 另外,除了% char之外,我不知道如何分辨整個percent字符串

這將滿足您的需求:

\b                     -- word boundary
\d+                    -- one or more digits
(?:\.\d+)?             -- optionally followed by a period and one or more digits
\b                     -- word boundary
\s+                    -- one or more spaces
(?!%|percent)          -- NOT followed by a % or the word 'percent'

- 編輯 -

這里的肉是在最后一行使用“否定前瞻”,如果在數字和一個或多個空格之后出現任何百分號或文字“百分比”,則導致匹配失敗。 JavaScript RegExps中負向前瞻的其他用法可以在Negative lookahead Regular Expression中找到

--2ND EDIT--恭喜Enrico解決最常見的案例,但下面的解決方案是正確的,它包含幾個無關的運算符。 這是最簡潔的解決方案。

(                         -- start capture
  \d+                     -- one or more digits
  (?:[\.,]\d+)?           -- optional period or comma followed by one or more digits
  \b                      -- word boundary
  (?!                     -- start negative lookahead
    (?:[\.,]\d+)          -- must not be followed by period or comma plus digits
  |                       --    or
    (?:                   -- start option group
      \s?%                -- optional space plus percent sign
    |                     --   or
      \spercent           -- required space and literal 'percent'
    )                     -- end option group
  )                       -- end negative lookahead
)                         -- end capture group

這是實現它的強大方法,它也提取數字。

(\b\d+(?:[\.,]\d+)?\b(?!(?:[\.,]\d+)|(?:\s*(?:%|percent))))

它類似於Rob的正則表達式,但它適用於所有情況。

(                          -- capturing block
  \b                       -- word boundary
  \d+                      -- one or more digits
  (?:[\.,]\d+)?            -- optionally followed by a period or a comma
                              and one or more digits
  \b                       -- word boundary
  (?!                      -- not followed by
    (?:[\.,]\d+)           -- a period or a comma and one or more digits
                              [that is the trick]
    |                      -- or
    (?:\s*(?:%|percent))   -- zero or more spaces and the % sign or 'percent'
  )
)

使用否定先行而不是否定的字符類:

/\d+(?:[,.]\d+)?(?!\s*(?:percent|%))/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM