【问题标题】:How to search a string with parentheses using regular expression? [duplicate]如何使用正则表达式搜索带括号的字符串? [复制]
【发布时间】:2019-12-26 06:25:23
【问题描述】:

我有一个包含以下字符串的 txt 文件:

   A 123
   B  456
   Ab(123)
   ......

我想在txt文件中搜索Ab(123)

我尝试过的:

re.search(r'Ab(123)',string)

【问题讨论】:

  • 正则表达式中的括号是为捕获组保留的,因此需要用反斜杠转义

标签: python regex python-3.x string parentheses


【解决方案1】:

Ab\(123\)

在正则表达式中,有 12 个具有特殊含义的字符:反斜杠\、插入符号^、美元符号$、句点或点.、竖线或竖线符号| 、问号?、星号或星号*、加号+、左括号(、右括号)、左方括号[和左大括号{,这些特殊字符通常称为metacharacters,如果用作文字,应使用反斜杠Ab\(123\) 进行转义。
这可以使用re.escape()

自动实现
import re
string = "some text Ab(123) and more text"
if re.search(re.escape("Ab(123)"),string):
  print("match")

【讨论】:

    【解决方案2】:

    如果您的目标只是提取带括号的行,您是否真的需要正则表达式。

    您可以使用以下方法:

    输入:

    $ cat parentheses.txt 
    A 123
    B  456
    Ab(123)
    uV(a5afgsg3)
    A 123
    

    输出:

    $ python parentheses.py 
    ['Ab(123)', 'uV(a5afgsg3)']
    

    代码:

    with open('parentheses.txt') as f:
        content = f.readlines()
    content = [x.strip() for x in content if '(' in x and ')' in x]
    print(content)
    

    如果你真的想使用正则表达式:

    import re
    
    s = """
    A 123
    B  456
    Ab(123)
    uV(a5afgsg3)
    A 123
    """
    print(re.findall(r'^.*?\(.*?\).*$',s,re.MULTILINE))
    

    输出:

    ['Ab(123)', 'uV(a5afgsg3)']
    

    演示: https://regex101.com/r/PGsguA/1

    【讨论】:

      【解决方案3】:

      有12个有特殊含义的字符,你可以在前面加上\转义到它的字面意思。

      re.search(r'Ab\(123\)',string)
      
      # or re.findall(r'Ab\(123\)',string)
      

      详情请查看https://regex101.com/r/1bb8oz/1

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-28
        • 2015-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-10
        • 1970-01-01
        相关资源
        最近更新 更多