正则表达式尝试使用多个条件或向后搜索

发布于 2025-01-15 07:06:41 字数 378 浏览 2 评论 0原文

欣赏正则表达式,但仍处于开始阶段。

我尝试了很多解决方法,但不知道如何解决我的问题。

字符串 A : 4 x 120glgt

字符串 B : 120glgt

我希望正确的正则表达式返回 120 作为 "x" 之后的数字。 但有时不会有“x”。因此,无论是[A]还是[B],都在寻找一种独特的方法。

我尝试:

  1. 的 END St​​art 开始搜索
  2. 从“x”之后

我显然有一些语法问题,并且不太明白 (?=)

(?=[ ^x])(?=[0-9]+)

期待在您的帮助下学习

Appreciating regex but still beginning.

I tried many workarounds but can't figure how to solve my problem.

String A : 4 x 120glgt

String B : 120glgt

I'd like the proper regex to return 120 as the number after "x".
But sometimes there won't be "x". So, be it [A] or [B] looking for one unique approach.

I tried :

  1. to start the search from the END
  2. Start right after the "x"

I clearly have some syntax issues and didn't quite get the logic of (?=)

(?=[^x])(?=[0-9]+)

So looking forward to learn with your help

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

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

发布评论

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

评论(1

客…行舟 2025-01-22 07:06:41

当您标记 PCRE 时,您可以选择匹配前导数字后跟 x 并使用 \K 清除匹配缓冲区以仅匹配其后面的数字。

^(?:\d+\h*x\h*)?\K\d+

模式匹配:

  • ^ 字符串开头
  • (?:\d+\h*x\h*)? 可以选择匹配 1+ 位数字,后跟 x 可选空格之间
  • \K 忘记目前为止匹配的内容
  • \d+ 匹配 1+ 位数字

查看 正则表达式演示

如果您想使用前瞻变体,您可以使用

\d+(?=[^\r\n\dx]*$)

此模式匹配:

  • \d+ 匹配 1+ 位数字
  • (?= 正向前瞻,断言右侧是什么
    • [^\r\n\dx]*$ 匹配除数字、x 或换行符之外的任何字符的可选重复
  • ) 关闭前视

请参阅另一个正则表达式演示

As you tagged pcre, you could optionally match the leading digits followed by x and use \K to clear the match buffer to only match the digits after it.

^(?:\d+\h*x\h*)?\K\d+

The pattern matches:

  • ^ Start of string
  • (?:\d+\h*x\h*)? Optionally match 1+ digits followed by x between optional spaces
  • \K Forget what is matched so far
  • \d+ Match 1+ digits

See a regex demo.

If you want to use a lookahead variant, you might use

\d+(?=[^\r\n\dx]*$)

This pattern matches:

  • \d+ Match 1+ digits
  • (?= Positive lookahead, assert what is to the right is
    • [^\r\n\dx]*$ Match optional repetitions of any char except a digit, x or a newline
  • ) Close the lookahead

See another regex demo.

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