python - 使用正则表达式重新排序字符串

标签 python regex replace location

我想将第一次出现的日期或通常的正则表达式放在文本的开头:

例子: “我在 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/

相关文章:

python - softmax python 计算

python - 服务器关闭之前后台线程未启动

python - 使用 Pandas 基于正则表达式分离列数据

R 一次查找和替换多个脚本

python - Heroku 上的 Flask 和 Celery : sqlalchemy. exc.DatabaseError : (psycopg2. DatabaseError) SSL 错误:解密失败或错误记录 mac

JAVA REGEX - 使用 "?"作为分隔符分割字符串

php - 从Embed iframe获取YouTube图片

mysql - 通过表进行 SQL 替换

javascript - 未从 JavaScript 中的文本替换中获得预期结果

python遍历列表