我想将第一次出现的日期或通常的正则表达式放在文本的开头:
例子:
“我在 2012 年 9 月 1 日出去,比 2012 年 1 月 15 日好”
我想得到
“2012 年 9 月 1 日,我出去了,比 2012 年 1 月 15 日好多了”
我正在考虑将 "1 sep 2012"
替换为 ",1 sep 2012,"
然后从 ","
但我不知道该写什么来代替 replace_with
:
line = re.sub(r'\d+\s(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s\d{4}', 'replace_with', line, 1)
有什么帮助吗?
最佳答案
使用 capture groups :
>>> import re
>>> s = "I went out on 1 sep 2012 and it was better than 15 jan 2012"
>>> r = re.compile('(^.*)(1 sep 2012 )(.*$)')
>>> r.sub(r'\2\1\3',s)
'1 sep 2012 I went out on and it was better than 15 jan 2012'
括号捕获部分字符串:
(^.*) # Capture everything from the start of the string
(1 sep 2012 ) # Upto the part we are interested in (captured)
(.*$) # Capture everything else
然后只需在替换 `\2\1\3'
中重新排序捕获组 注意: 引用捕获组需要原始字符串 r'\2\1\3'
。我示例中的第二组只是文字字符串 (1 sep 2012 )
但当然这可以是任何正则表达式,例如您创建的正则表达式(带有额外的 \s
最后):
(\d+\s(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s\d{4}\s)
>>> r = re.compile(r'(^.*)(\d+\s(?:aug|sep|oct|nov)\s\d{4}\s)(.*$)')
>>> r.sub(r'\2\1\3',s)
'1 sep 2012 I went out on and it was better than 15 jan 2012'
来自 docs.python.org :
When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change.
关于python - 使用正则表达式重新排序字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14153364/