我使用python2.7,并试图将某个字符串与此结构匹配:
INPUT = 'abc-1-2 abc-2-3 abc-1-1 - TYP1 xyz-2-3 xyzzz - TYP2 ooop-1-1 abc-3-3 bbb - TYP3'
EXPECTED_OUTPUT = [
'abc-1-2 abc-2-3 abc-1-1 - TYP1',
'xyz-2-3 xyzzz - TYP2',
'ooop-1-1 abc-3-3 bbb - TYP3']这是我尝试过的解决方案,但它不起作用:在线演示
发布于 2017-02-27 16:44:03
我想这就是你要找的:
".+?TYP\d+"发布于 2017-02-27 17:05:28
下面的regex应该这样做:
\b.*?-\s.*?(?:\s|$)请参阅https://regex101.com/r/hCWuF3/2
python
import re
regex = ur"\b.*?-\s.*?(?:\s|$)"
str = "abc-1-2 abc-2-3 abc-1-1 - TYP1 xyz-2-3 xyzzz - TYP2 ooop-1-1 abc-3-3 bbb - TYP3"
matches = re.finditer(regex, str)
for matchNum, match in enumerate(matches):
matchNum = matchNum + 1
print ("{match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))发布于 2017-02-27 17:44:44
>>> re.findall(r'\S.*? - \S+', INPUT)
['abc-1-2 abc-2-3 abc-1-1 - TYP1', 'xyz-2-3 xyzzz - TYP2', 'ooop-1-1 abc-3-3 bbb - TYP3']解释:
'\S' # any non-space character
'.*?' # (.) any character (*) zero or more times (?) non-greedy (match as few as possible)
' - ' # literal space dash space
'\S' # any non-space character
'+' # one or more timeshttps://stackoverflow.com/questions/42491041
复制相似问题