【问题标题】:How to extract substring in python using regular expression如何使用正则表达式在python中提取子字符串
【发布时间】:2018-03-25 03:27:49
【问题描述】:

我有一个字符串,例如this is title [[this is translated title]],我需要提取这两个子字段。 this is title, this is translated title

我尝试使用正则表达式,但无法完成。

def translate(value):
    # Values are paseed in the form of 
    # "This is text [[This is translated text]]"
    import re
    regex = r"(.+)(\[\[.*\]\])"
    match = re.match(regex, value)
    # Return text
    first = match.group(1)

    # Return translated text
    second = match.group(2).lstrip("[[").rstrip("]]")

    return first, second

但这会失败。当字符串为“简单纯文本”时

【问题讨论】:

  • 你所拥有的似乎有效。有什么问题?

标签: python regex python-3.x python-3.5


【解决方案1】:

我找到了一种不使用正则表达式的简单方法

def trns(value):
    first, second =  value.rstrip("]]").split("[[")
    return first, second

【讨论】:

    【解决方案2】:

    您必须使用正则表达式 r'((\w.*)\[\[(\w.*)\]\]|(\w.*))group(1) 中产生 this is title 并在 group(2) 中产生 this is translate title 所以您的代码应该是 p>

    def translate(value):
        # value = "This is text [[This is translated text]]"
        import re
        regex = r'((\w.*)\[\[(\w.*)\]\]|(\w.*))'
        match = re.match(regex, value)
        result = [x for x in match.groups() if x and x!=value]
        return result if result else value
    

    这会按预期返回。

    要测试您的正则表达式,您可以使用this.

    【讨论】:

    • 我认为这会因 value="this is only text" 而失败
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多