正则表达式尝试使用多个条件或向后搜索
欣赏正则表达式,但仍处于开始阶段。
我尝试了很多解决方法,但不知道如何解决我的问题。
字符串 A : 4 x 120glgt
字符串 B : 120glgt
我希望正确的正则表达式返回 120 作为 "x"
之后的数字。 但有时不会有“x”
。因此,无论是[A]还是[B],都在寻找一种独特的方法。
我尝试:
- 的 END Start 开始搜索
- 从“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 :
- to start the search from the END
- 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您标记 PCRE 时,您可以选择匹配前导数字后跟 x 并使用
\K
清除匹配缓冲区以仅匹配其后面的数字。模式匹配:
^
字符串开头(?:\d+\h*x\h*)?
可以选择匹配 1+ 位数字,后跟x
可选空格之间\K
忘记目前为止匹配的内容\d+
匹配 1+ 位数字查看 正则表达式演示。
如果您想使用前瞻变体,您可以使用
此模式匹配:
\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.The pattern matches:
^
Start of string(?:\d+\h*x\h*)?
Optionally match 1+ digits followed byx
between optional spaces\K
Forget what is matched so far\d+
Match 1+ digitsSee a regex demo.
If you want to use a lookahead variant, you might use
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 lookaheadSee another regex demo.