1

我是正则表达式的新手,我想对我的代码提出一些建议。我在python中有以下代码:

import re

textToSearch = """ 
hello{
    @hi {
        I want this text
    }

    @hola {
        I don't want this text
    }
} 
"""

regex= r'(?<=@hi {)[^}]*'
result = re.findall(regex,textToSearch)

print(result) 

#Output = ['\n 我想要这个文本\n']

我想要的输出是:

@hi { #这里的一切 }

包括@hi前导空格花括号

我将不胜感激任何解决此问题的建议。谢谢你。

4

3 回答 3

0

您可以hi在匹配中包含而不是将其断言到左侧,并使用 . 匹配不带换行符的空格[^\S\r\n]*

如果您还想匹配前导换行符,您可以使用\s*

[^\S\r\n]*@hi\b[^\S\r\n]*{[^{}]*}

查看正则表达式演示Python 演示

模式匹配:

  • [^\S\r\n]*匹配 0+ 个没有换行符的空白字符
  • @hi\b匹配@hi
  • [^\S\r\n]*匹配 0+ 个没有换行符的空白字符
  • {[^{}]*}使用匹配任何字符(包括匹配换行符)的否定字符类匹配from {until}

例如

import re

textToSearch = """ 
hello{
    @hi {
        I want this text
    }

    @hola {
        I don't want this text
    }
} 
"""

regex= r'[^\S\r\n]*@hi\b[^\S\r\n]*{[^{}]*}'
result = re.findall(regex,textToSearch)

print(result) 

输出

['    @hi {\n        I want this text\n    }']
于 2021-05-15T17:51:35.387 回答
0

您可以使用此正则表达式模式来匹配您的文本:

pattern = r'@hi \{\n\s+(?P<text>[\w ]+)\n\s+\}'
match_result = re.search(pattern, textToSearch)

# To get all the found value
match_found = match_result.group(0)

# To get the text only
needed_text = match_result['text']

print(match_found)
print(needed_text)

这是模式的解释:

  • \n换行
  • \s空间
  • \w用于字母数字
  • (?P<group_name>[pattern_value])团体搜索
  • +一个或多个价值
于 2021-05-15T17:55:35.220 回答
0

使用正则表达式标志来扩展含义,^.可以使用以下模式:

import re

textToSearch = """ 
hello{
    @hi {
        I want this text
    }

    @hola {
        I don't want this text
    }
} 
"""

# regex = '(?sm)^\s*@hi\s*{.*?}'  # non-verbose version

regex= r'''(?smx)  # DOTALL|MULTILINE|VERBOSE flags
           ^       # start of line (due to MULTILINE)
           \s*     # any amount of whitespace
           @hi     # match exactly these characters
           \s*     # any amount of whitespace
           {.*?}   # capture everything up between braces (due to DOTALL)
        ''' 

result = re.findall(regex,textToSearch)
print(result) 

输出:

['    @hi {\n        I want this text\n    }']
于 2021-05-15T18:51:21.867 回答