如何在多字符串变量中的特定文本后使用正则表达式匹配随机数?

发布于 2025-01-16 15:11:45 字数 287 浏览 4 评论 0原文

在python中,我想通过在多字符串变量中搜索“Beginning Supply”来捕获一个随机数“100000000000000000”,如下所示,

import re

message = """Test
- 55244
Graph
- Tools
Beginning Supply
- 100000000000000000
Name
- Text2
Type"""

pattern = re.compile(r"Total.Supply...(\d+)")
pattern.match(message)

In python, I want to capture a random number lets say '100000000000000000' by searching for 'Beginning Supply' in a multi string variable as shown below,

import re

message = """Test
- 55244
Graph
- Tools
Beginning Supply
- 100000000000000000
Name
- Text2
Type"""

pattern = re.compile(r"Total.Supply...(\d+)")
pattern.match(message)

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

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

发布评论

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

评论(1

梦里梦着梦中梦 2025-01-23 15:11:45

默认情况下,. 不捕获\n 字符。为了实现这一点,您必须在模式中使用 DOTALL 标志。

如果你想使用 match

import re

message = """Test
- 55244
Graph
- Tools
Beginning Supply
- 100000000000000000
Name
- Text2
Type"""

pattern = re.compile(r"(?:.*)(Beginning Supply...)(?P<num>\d+)(?:.*)", flags=re.DOTALL)
number = pattern.match(message).group("num")

如果你想使用 findall

import re

message = """Test
- 55244
Graph
- Tools
Beginning Supply
- 100000000000000000
Name
- Text2
Type"""

pattern = re.compile(r"Beginning Supply...(\d+)", flags=re.DOTALL)
number = pattern.findall(message)[0]

注意:re.match 必须匹配整个字符串,否则它将返回

By default, . does not capture \n characters. In order to achieve that you must use the DOTALL flag in your pattern.

If you want to use match:

import re

message = """Test
- 55244
Graph
- Tools
Beginning Supply
- 100000000000000000
Name
- Text2
Type"""

pattern = re.compile(r"(?:.*)(Beginning Supply...)(?P<num>\d+)(?:.*)", flags=re.DOTALL)
number = pattern.match(message).group("num")

If you want to use findall:

import re

message = """Test
- 55244
Graph
- Tools
Beginning Supply
- 100000000000000000
Name
- Text2
Type"""

pattern = re.compile(r"Beginning Supply...(\d+)", flags=re.DOTALL)
number = pattern.findall(message)[0]

NOTE: re.match must match the entire string or else it will return None

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