Python 使用正则表达式对字符串重新排序
我想将日期或正则表达式的第一次出现带到文本的开头: 例如:Python 使用正则表达式对字符串重新排序,python,regex,replace,location,Python,Regex,Replace,Location,我想将日期或正则表达式的第一次出现带到文本的开头: 例如: “我于2012年9月1日外出,比2012年1月15日要好” 我想得到 “2012年9月1日,我出去了,比2012年1月15日好多了” 我正在考虑将“2012年9月1日”替换为”,2012年9月1日“,然后从”中删除字符串,“”,但我不知道写什么来代替替换为: line = re.sub(r'\d+\s(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s\d{4}', 'replace
“我于2012年9月1日外出,比2012年1月15日要好”
我想得到
“2012年9月1日,我出去了,比2012年1月15日好多了”
我正在考虑将“2012年9月1日”
替换为”,2012年9月1日“
,然后从”中删除字符串,“
”,但我不知道写什么来代替替换为:
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 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'
。我的示例中的第二个组只是文本字符串(2012年9月1日)
,但当然这可以是任何regexp,比如您创建的一个(末尾有一个额外的\s
):
发件人:
当出现“r”或“r”前缀时,反斜杠后面的字符将包含在字符串中,而不作任何更改
你在使用什么语言?你没有使用足够的捕获组…暂时忘掉Python吧。请浏览一些正则表达式教程。上面re.sub()
中的第一个参数并不能满足您的需要,尽管python re文档非常好
(^.*) # Capture everything from the start of the string
(1 sep 2012 ) # Upto the part we are interested in (captured)
(.*$) # Capture everything else
(\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'