在正则表达式匹配中使用环视或忽略非捕获

发布于 2024-11-27 13:14:24 字数 592 浏览 4 评论 0原文

考虑以下字符串:ABC。我想使用正则表达式捕获以下组:

Group1: AC
Group2: B

这两个组都必须使用单个正则表达式捕获。我无法控制代码,因此子匹配或捕获组不会有帮助。

我已经尝试过两个非捕获组并环顾四周。

对于非捕获组,比赛仍然是最终结果的一部分。

(?<Group1>a(?:(?<Group2>b))c)

Group1: ABC # 不对,因为 B 是比赛的一部分。 Group2:B

通过环视,Group2 不会被消耗,并且前瞻之后的正则表达式应该再次匹配 Group2 的内容,其中将其作为 Group1 的一部分包含在内。

(?<Group1>a(?=(?<Group2>b))bc)

Group1: ABC # 不对,因为 B 是比赛的一部分。 Group2: B

我怎样才能忽略 Group1 比赛中的“B”?

非常感谢任何有关解决此问题的帮助。

谢谢, 巴拉吉

Consider the following string: ABC. I would like to capture the following groups using a regular expression:

Group1: AC
Group2: B

Both the groups have to be captured using a single regular expression. I do not have control over the code, so sub-matches or capture groups will not help.

I've tried both non-capturing groups and look arounds.

With a Non-Capturing group, the match is still a part of the final result.

(?<Group1>a(?:(?<Group2>b))c)

Group1: ABC # Not right as B is part of the match. Group2: B

With a lookaround, Group2 is not consumed and the regex following the look ahead should match the contents of Group2 again which includes it as part of Group1.

(?<Group1>a(?=(?<Group2>b))bc)

Group1: ABC # Not right as B is part of the match.
Group2: B

How can I ignore "B" as part of the Group1 match?

Any help on getting around this is greatly appreciated.

Thanks,
Balaji

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无声无音无过去 2024-12-04 13:14:25

你不能。正则表达式引擎无法将非线性子匹配粘贴到单个匹配中。任何匹配都必须是原始文本中的连续字符。

You can't. Regex engines can't paste together nonlinear submatches into a single match. Any match must be a succession of characters from the original text.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文