Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用正则表达式对字符串重新排序_Python_Regex_Replace_Location - Fatal编程技术网

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'