![](/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.