问题描述
我正在使用re module的python re.compile()进行拆分
name1:A=a name2:B=b name3:C=c d
进入
name1 A=a,name2 B=b,name3 C=c d
这是我的正则表达式
(\w+): (A|B|C)(=[\w+\s*\w*]+)
但是最终给我的输出是:
名称1:A =名称2 :B = b 名称3:C = c d
粗体文本是它正在捕获的文本。单词A,B和C来自预定义的标题列表,即只有这些才会出现在“ =”符号之前。由于这是我的第一个问题,请让我知道是否需要更多信息。
我希望很清楚。
预先感谢:D
解决方法
代替拆分,您可以尝试匹配相关部分:
import re
text = "name1:A=a name2:B=b name3:C=c d"
rx = re.compile(r'\w+:(?:\w+(?:=\w+)?(?:\s+|$))+')
for match in rx.finditer(text):
name,rest = match.group(0).split(":")
print("{},{}".format(name,rest))
这产生
name1,A=a
name2,B=b
name3,C=c d
请参见regex101.com上的a demo for the expression。
,您需要指示下一场比赛的边缘。在这里,换行或文本结尾完成了工作。
(\w+): [ABC](=\w+\s*\w*)(?:\n|$)
顺便说一句,源中包含一个“,”,而在正则表达式中,名称后使用了“:”。
这里是一个单行字符串的解决方案。
(\w+): (A|B|C)(=\w+\s*\w*?\(?:\s+|$))
,
这不能完全回答您的问题,但是很高兴知道无需使用正则表达式就可以得到想要的东西:
import itertools
my_string = "name1 A:a name2 B:b name3 C:c d"
# split on whitespaces
split_string = my_string.split()
# get only the even elements
evens = split_string[0::2]
# get only the odd elements
odds = split_string[1::2]
# get the A=a format you want
new_odds = [odd.replace(":","=") for odd in odds]
# zip the lists together,without losing any elements from the longer list
zipped = itertools.zip_longest(evens,new_odds)
# make this zip a list for us to view it
zipped_as_list = [x for x in zipped]
# look at what we made
print(zipped_as_list)
我不知道您到底想要什么形状的数据,也不知道尾随d
的含义。
如果您只能使用split,请在正则表达式下面使用。
\s(?=\w+:)|:
示例
import re
text="name1:A=a name2:B=b name3:C=c d"
print(re.split(r"\s(?=\w+:)|:",text))
输出
['name1','A=a','name2','B=b','name3','C=c d']