import re
lines = ["TEST/1000", "TEST2/1000", "TEST3/1000"]
pattern = "TEST\d*(?=/)" # Take any string beginning with TEST, followed by 0 or more digits and a / character
for line in lines:
match = re.match(pattern, line)
if match is not None:
print(match.group(0)) # match.group(0) returns the whole matched string, and not a part of it
else:
print("No match for %s" % line)
在python中,可以使用split() function,它返回按指定字符拆分的元素数组。然后得到第一个元素:
我会选择
split
解决方案,但是如果您正在寻找一个更完整同时简单的解决方案(假设您知道regex,不管怎样,它应该属于任何程序员的知识),那么您可以使用标准库re module中的一些快捷方法。在使用相同数据的示例如下:
在我的设置中,在
^{pr2}$test.py
文件中运行此脚本会产生:相关问题 更多 >
编程相关推荐