![](/img/trans.png)
[英]Regex to capture groups and ignore last two characters where one is optional
[英]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'
'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.