可以在正则表达式的一个位置匹配但不能在另一个位置匹配(例如位置异或)?

发布于 2024-12-19 02:23:47 字数 791 浏览 4 评论 0原文

我希望在更大的正则表达式中创建多个子表达式,其中每个子表达式与输入中的一个位置或另一个位置的某些内容匹配,但不是在两个位置都匹配,最好每个“感兴趣的区域”使用相同的命名组。例如,我想匹配下面以斜体显示的数量单位和以粗体显示的货币单位。

  • 3.23 美元美元/加仑
  • 美元 3.23 英寸加仑
  • 4.50 加元 / 加仑
  • 1 加仑 @ 美元 3.23
  • 10 加仑。 @ $4.50 CAD

或者更一般地说:

  • stuffmorestuffXXXyetmorestuff
  • stuffXXX morestuff

其中 stuffmorestuff 可以是一组复杂的子表达式。

似乎可以使用

  • 组堆栈推送/弹出
  • 平衡组
  • 环视

的某种组合,但我不确定如何继续。它是否归结为交替(|)或具有不同表达式的多次传递(我认为这相当于同一件事)?

I am looking to create several sub-expressions in a larger regular expression, where each subexpression matches something at one place in the input or another place, but not in both places, preferably using the same named group per "area of interest". For example, I'd like to match volume units in italics below, and currency units, shown in bold.

  • $3.23 USD / gal.
  • USD 3.23 in gallons
  • 4.50 CAD / gal
  • 1 gal @ USD 3.23
  • 10 gal. @ $4.50 CAD

Or more generally:

  • stuffmorestuffXXXyetmorestuff
  • stuffXXXmorestuff

where stuff and morestuff could be a complex set of sub-expressions.

It seems like it might be possible using some combination of

  • group stack push/pop
  • balancing groups
  • look-around

but I'm not sure how to proceed. Does it come down to alternations (|) or multiple passes with different expressions (which I suppose amounts to the same thing)?

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

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

发布评论

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

评论(1

壹場煙雨 2024-12-26 02:23:47

你可能必须使用交替,类似这样的东西?

^(stuffmorestuff)XXX(yetmorestuff)|(stuff)XXX(morestuff)$

但最终您将得到四个捕获组。如果您对多个组使用相同的组名称,则不确定 .NET 正则表达式引擎将如何运行。

You probably have to use alternation, something like this?

^(stuffmorestuff)XXX(yetmorestuff)|(stuff)XXX(morestuff)$

But you will end up with four capture groups. Not sure how the .NET regex engine will behave if you use the same group name for several groups.

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