簡體   English   中英

正則表達式捕獲可選字符

[英]Regex to capture optional characters

我想從一個較長的字符串中提取一個基本字符串 (Wax) 或 (noWax),如果該字符串是 Wax,則可能還有前后的任何數據。 我無法匹配下面列表中的最后一項 (noWax)。

任何人都可以展示他們的正則表達式肌肉嗎? 我是正則表達式的新手,因此只要找到以下所有匹配項,就歡迎提供優化建議。

我在 Regex101 中使用的是:


/(?<Wax>Wax(?:Only|-?\d+))/mg

原始字符串 需要在捕獲組中提取
Loc3_341001_WaxOnly_S212 純蠟
Loc4_34412-a_Wax4_S231 蠟4
Loc3a_231121-a_Wax-4-S451 蠟4
Loc3_34112_noWax_S311 無蠟

這是一種使用 條件的方法:

(?<Wax>(no)?Wax(?(2)|(?:Only|-?\d+)))

請參閱在線演示


  • (no)? : 可選的捕獲組。
  • (?如果.
    • (2) :測試捕獲組 2 是否存在 ( (no) )。 如果是,則什么也不做。
    • | : 或者。
    • (?:Only|-?\d+)

我假設需要以下匹配。

  • 比賽必須包括'Wax'
  • 'Wax'前面要有'_''_no' 如果匹配中包含后者'no'
  • 'Wax'后面可能跟有:
    • 'Only'后跟'_' ,在這種情況下'Only'是匹配項的一部分,或者
    • 一個或多個數字,后跟'_' ,在這種情況下,數字是匹配項的一部分,或者
    • '-'后跟一個或多個數字,然后是'-' ,在這種情況下, '-'后跟一個或多個數字是匹配的一部分。

如果這些假設是正確的,則字符串可以與以下正則表達式匹配:

(?<=_)(?:(?:no)?Wax(?:(?:Only|\d+)?(?=_)|\-\d+(?=-)))

演示

正則表達式可以分解如下。

(?<=_)            # positive lookbehind asserts previous character is '_'
(?:               # begin non-capture group
  (?:no)?         # optionally match 'no'
  Wax             # match literal
  (?:             # begin non-capture group
    (?:Only|\d+)? # optionally match 'Only' or >=1 digits
    (?=_)         # positive lookahead asserts next character is '_'
    |             # or
    \-\d+         # match '-' followed by >= 1 digits
    (?=-)         # positive lookahead asserts next character is '-'
  )               # end non-capture group
)                 # end non-capture group

暫無
暫無

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

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