我有一个字符串 “ OBNAME [来源:85复制:1标识符:TDEP],OBNAME [来源:85复制:1标识符:RDEP]”格式和输出必须是TDEP,RDEP是什么有效的提取方法?
test = 'OBNAME[origin:85 copy:1 identifier:TDEP],OBNAME[origin:85 copy:1 identifier:RDEP]'
test1 = test.replace('OBNAME','')
test2 = test1.split(',')
for dd in test2 :
#print(dd)
test4 = dd.split('identifier:')
test5 = test4[1]
channels = channels +','+ test5.replace(']','')
print(channels)
答案 0 :(得分:1)
您可以使用正则表达式:identifier:(.*?)]
这是在regex101.com上生成的代码:
https://regex101.com/r/t5ToQK/1
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"identifier:(.*?)]"
test_str = "'OBNAME[origin:85 copy:1 identifier:TDEP],OBNAME[origin:85 copy:1 identifier:RDEP]'"
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
答案 1 :(得分:1)
在这里,我们可以将一个简单的表达式与一个捕获组一起使用,并收集所需的输出,然后用逗号将它们加入:
Configuration
如果不需要空格,则可以将其简化为:
identifier:(\s+)?(.*?)(\s+)?\]
identifier:(.*?)\]
如果不需要此表达式,并且希望对其进行修改,请访问regex101.com上的此链接。
jex.im可视化正则表达式:
答案 2 :(得分:0)
您可以使用单个捕获组和否定的字符类来匹配]
:
\bidentifier:([^]]+)\]
这将匹配:
\bidentifer:
匹配标识符:以单词边界开头(
捕获组
[^]]+
匹配1次以上而不是]
)
关闭捕获组\]
匹配]