【问题标题】:How do I form a regex express to return all parts of the string prior to a [ [duplicate]如何形成正则表达式以在 [ [重复] 之前返回字符串的所有部分
【发布时间】:2021-07-27 09:23:21
【问题描述】:

我正在尝试形成一个正则表达式来匹配符合以下模式的字符串:

这就是我想要的[不是这个]

返回字符串应该是:

这就是我想要的

我尝试过的正则表达式是:

strings = ['这是我想要的[但不是这个]', '我应该坚持这部分[但这部分可以丢弃]']

使用这个表达式:re.search(r"(.*)[)", strings

输出是:

这就是我想要的[

我应该坚持这部分[

我也试过: re.search(r"(.*)(?![)

返回值是整个原始字符串。我已经使用索引编写了这个来查找“[”字符并从该字符开始删除所有内容,但我想知道如何使用正则表达式来完成。

谢谢。

编辑:

我尝试了两个正则表达式建议,但都不起作用。

#!/usr/bin/python

import re

strings = ['This is what I want [but not this]',
           'I should hold onto this part [but this part can be discarded]']


for string in strings:
    print(re.match("^[^\[]*(?:\[|$)",string).group(0))

输出:

这就是我想要的[

我应该坚持这部分[

【问题讨论】:

    标签: regex


    【解决方案1】:

    这将返回包含您要查找的字符串的组。

    ^(.+)\[
    

    regex101.com 上查看它。

    【讨论】:

    • 没用。我仍然在输出中返回了左括号。
    • 你需要拉群。
    【解决方案2】:

    您可以使用正则表达式模式^[^\[]*(?:\[|$):

    strings = ['This is what I want [but not this]', 'I should hold onto this part [but this part can be discarded]','no brackets here']
    output = [re.findall(r'^[^\[]*(?:\[|$)', x)[0] for x in strings]
    print(output)
    

    打印出来:

    ['This is what I want [', 'I should hold onto this part [', 'no brackets here']
    

    这里使用的正则表达式模式表示匹配:

    ^             from the start of the input
        [^\[]*    zero or more non [ characters, until hitting
        (?:\[|$)  and including either the first [ OR the end of the input
    

    请注意,我们保留您的输入字符串可能在任何地方都没有[ 的可能性,在这种情况下,我们会将整个输入作为匹配项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 2021-02-15
      • 2017-01-24
      相关资源
      最近更新 更多