【问题标题】:Reorder string using regular expressions使用正则表达式重新排序字符串
【发布时间】:2012-12-18 16:02:44
【问题描述】:

我想将第一次出现的日期或一般的正则表达式带到我的文本开头:

示例: "I went out on 1 sep 2012 and it was better than 15 jan 2012" 我想得到 "1 sep 2012, I went out on and it was better than 15 jan 2012"

我正在考虑用",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)

有什么帮助吗?

【问题讨论】:

  • 你使用什么语言?
  • 您没有使用足够的捕获组...
  • 暂时忘记 Python。请查看一些正则表达式教程。你在上面re.sub() 中的第一个参数不会得到你想要的。
  • 虽然python re doc很好docs.python.org/2/library/re.html

标签: python regex replace location


【解决方案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

当存在 'r' 或 'R' 前缀时,反斜杠后面的字符将直接包含在字符串中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多