正则表达式捕获可选字符
我想从较长的字符串中提取基本字符串 (Wax) 或 (noWax),如果该字符串是 Wax,则还可能包含之前和之后的任何数据。我无法匹配下面列表中的最后一项(noWax)。
任何人都可以展示他们的正则表达式肌肉吗?我对正则表达式相当陌生,因此只要找到下面的所有匹配项,就欢迎提供优化建议。
我在 Regex101 中使用的内容:
/(?<Wax>Wax(?:Only|-?\d+))/mg
原始字符串 | 需要在捕获组中提取 |
---|---|
Loc3_341001_WaxOnly_S212 | WaxOnly |
Loc4_34412-a_Wax4_S231 | Wax4 |
Loc3a_231121-a_Wax-4-S451 | Wax-4 |
Loc3_34112_noWax_S311 | noWax |
I want to pull out a base string (Wax) or (noWax) from a longer string, along with potentially any data before and after if the string is Wax. I'm having trouble getting the last item in my list below (noWax) to match.
Can anyone flex their regex muscles? I'm fairly new to regex so advice on optimization is welcome as long as all matches below are found.
What I'm working with in Regex101:
/(?<Wax>Wax(?:Only|-?\d+))/mg
Original string | need to extract in a capturing group |
---|---|
Loc3_341001_WaxOnly_S212 | WaxOnly |
Loc4_34412-a_Wax4_S231 | Wax4 |
Loc3a_231121-a_Wax-4-S451 | Wax-4 |
Loc3_34112_noWax_S311 | noWax |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种方法,使用 条件:
请参阅在线 < a href="https://regex101.com/r/XqLWv1/1" rel="nofollow noreferrer">演示。
(否)?
:可选捕获组。(?
如果。(2)
:测试捕获组 2 是否存在 ((no)
)。如果是这样,则什么也不做。|
:或者。(?:仅|-?\d+)
Here is one way to do so, using a conditional:
See the online demo.
(no)?
: Optional capture group.(?
If.(2)
: Test if capture group 2 exists ((no)
). If it does, do nothing.|
: Or.(?:Only|-?\d+)
我认为需要以下匹配。
'Wax'
'Wax'
前面应有'_'
或'_no'
>。如果后面的'no'
包含在匹配中。'Wax'
后面可能跟着:'Only'
后跟'_'
,在这种情况下,'Only'
是匹配的一部分,或者'_'
,在这种情况下,这些数字是匹配的一部分,或者'-'
后跟一个或多个数字,然后是'-'
,在这种情况下'-'
后跟一个或多个数字是匹配的一部分。如果这些假设正确,则可以将字符串与以下正则表达式进行匹配:
Demo
正则表达式可以细分如下。
I assume the following match is desired.
'Wax'
'Wax'
is to be preceded by'_'
or by'_no'
. If the latter'no'
is included in the match.'Wax'
may be followed by:'Only'
followed by'_'
, in which case'Only'
is part of the match, or'_'
, in which case the digits are part of the match, or'-'
followed by one or more digits, followed by'-'
, in which case'-'
followed by one or more digits is part of the match.If these assumptions are correct the string can be matched against the following regular expression:
Demo
The regular expression can be broken down as follows.