如何在字符串中找到数据?

发布于 2025-02-08 08:46:18 字数 1463 浏览 1 评论 0原文

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

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

发布评论

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

评论(2

南…巷孤猫 2025-02-15 08:46:18

使用 re.findall 。正则:
r'^(。*\ s)\ s+id:\ s*(\ d+)\ s+type:\ s*(。+)
^:String的开始。
。*:重复0次或更多次的任何字符。
\ s:非Whitespace字符。
\ s+:whitespace字符,重复1次或更多次。
\ d+:重复1次或更多次的数字。
(模式):捕获模式并将其返回。在这里,我们捕获3种模式。

import re

string = "Wacom Bamboo Connect Pen stylus   id: 15  type: STYLUS"

lst = re.findall(r'^(.*\S)\s+id:\s*(\d+)\s+type:\s*(.+)', string)

# The first match (list element) is a tuple. Extract it:
lst = list(lst[0])
lst[1] = int(lst[1])
print(lst)
# ['Wacom Bamboo Connect Pen stylus', 15, 'STYLUS']

Use re.findall. The regex:
r'^(.*\S)\s+id:\s*(\d+)\s+type:\s*(.+)' means:
^ : start of the string.
.* :any character, repeated 0 or more times.
\S : non-whitespace character.
\s+ : whitespace character, repeated 1 or more times.
\d+ : any digit, repeated 1 or more times.
(PATTERN) : capture the patterns and return it. Here we capture 3 patterns.

import re

string = "Wacom Bamboo Connect Pen stylus   id: 15  type: STYLUS"

lst = re.findall(r'^(.*\S)\s+id:\s*(\d+)\s+type:\s*(.+)', string)

# The first match (list element) is a tuple. Extract it:
lst = list(lst[0])
lst[1] = int(lst[1])
print(lst)
# ['Wacom Bamboo Connect Pen stylus', 15, 'STYLUS']
走走停停 2025-02-15 08:46:18

要匹配第一个字符串在ID之前:

.*(?=(id:))

要匹配 id 您需要:

(?<=id:.*)(\d*)(?=.*type)

匹配类型您需要:

(?<=type:.*)(\w+)

我建议您有查看 lookaheads and lookbehinds

To match the first string before id you need:

.*(?=(id:))

To match the id you need:

(?<=id:.*)(\d*)(?=.*type)

To match the type you need:

(?<=type:.*)(\w+)

I would suggest you have a look at lookaheads and lookbehinds.

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