【问题标题】:Get pattern depends of input string获取模式取决于输入字符串
【发布时间】:2023-01-19 00:48:06
【问题描述】:

是否可能,正则表达式应该如何在右括号之后获取所有内容,或者如果根本没有括号则获取所有内容?

例子:

可能的输入 1:

[12,45] some text

可能的输入 2: 一些文字

期望得到:

 some text

我发现有条件的 lookbehing 之类的东西,并尝试过:

(?(?<=\])((?<=\])(.*))|(.*))

但没有用。

这适用于带括号的输入:

(?<=\])(.*)

这适用于没有括号的输入:

(.*)

但是是否有可能得到一个表达式来匹配两种输入情况?

【问题讨论】:

    标签: regex


    【解决方案1】:

    这个正则表达式,你需要OR又名|

    (?<=]s|^)[ws]+
    #      ^ 
    #      |
    #    there
    

    正则表达式匹配如下:

    Node Explanation
    (?&lt;= look behind to see if there is:
    ] ]
    s whitespace ( , , , , and " ")
    | OR
    ^ the beginning of the string
    ) end of look-behind
    [ws]+ any character of: word characters (a-z, A- Z, 0-9, _), whitespace ( , , , , and " ") (1 or more times (matching the most amount possible))

    在线演示

    regex101

    【讨论】:

    • 我不知道括号后是否会有空格(如果没有,它仍然可以接受),我还在文本中添加了对变音符号的识别(在我的特定语言中可能是那种符号,所以我需要把它考虑进去考虑)并且它完美地工作!感谢我的新正则表达式:(?<=]|^)[wsÀ-ž]+
    【解决方案2】:

    在 python 中,你可以使用来自 re 包的命令:

    代码:

    import re
    
    text = "[12,45] some text
    some text"
    output = re.sub(r'[.*?]s?', '', text)
    print(output)
    

    输出:

    some text
    some text
    

    正则表达式为消除方括号内和包括方括号的内容。

    • [.*?]s?

    • [ = 左方括号

    • .*? = 零个或多个字符(可选)

    • ] = 右方括号

    • s? = 空格(可选)

    【讨论】:

      猜你喜欢
      • 2012-04-10
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多