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']
发布评论
评论(2)
使用
re.findall
。正则:r'^(。*\ s)\ s+id:\ s*(\ d+)\ s+type:\ s*(。+)
^
:String的开始。。*
:重复0次或更多次的任何字符。\ s
:非Whitespace字符。\ s+
:whitespace字符,重复1次或更多次。\ d+
:重复1次或更多次的数字。(模式)
:捕获模式并将其返回。在这里,我们捕获3种模式。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.要匹配第一个字符串在ID之前:
要匹配 id 您需要:
匹配类型您需要:
我建议您有查看 lookaheads and lookbehinds 。
To match the first string before id you need:
To match the id you need:
To match the type you need:
I would suggest you have a look at lookaheads and lookbehinds.