用python求多行模式的正则表达式

2024-05-13 04:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,我试图匹配一个模式,并替换为其他字符串,但匹配行太大,出现在多行;因此,我的模式是匹配第一行,并替换该行只。你知道吗

示例-

m_pMainSceneManager->PushScene<ConfigurationSpecificHelpScreens>(MainScreenPriority::HelpScreens, &m_ContextTable
            , L"HelpScreens.mercury");

这是两行- 直到上下文表(&m_ContextTable)在一行中 , L"HelpScreens.mercury");在另一行。你知道吗

有这么多正则表达式,我也尝试了这个正则表达式-

cpat = re.compile(r'.*m_pMainSceneManager->PushScene<ConfigurationSpecificHelpScreens>\(.*\n.*\)')

我在上面用re.MULTILINE试过,也没有用。但运气不好。你知道吗


Tags: 文件字符串re示例模式multilinecompilemercury
1条回答
网友
1楼 · 发布于 2024-05-13 04:25:17

可能,您应该使用flags=re.DOTALL。在这里阅读更多关于re.compile的信息:https://docs.python.org/2/library/re.htmlre.DOTALL表示包含换行符的搜索。你知道吗

>>> import re  
>>> print(re.match('.', '\n'))
None
>>> print(re.match('.', '\n', flags=re.DOTALL))
<_sre.SRE_Match object at 0x02B848E0>

在您的特殊情况下,您可以使用:

>>> s = '''m_pMainSceneManager->PushScene<ConfigurationSpecificHelpScreens>(MainScreenPriority::HelpScreens, &m_ContextTable
...             , L"HelpScreens.mercury");'''
>>> s
'm_pMainSceneManager->PushScene<ConfigurationSpecificHelpScreens>(MainScreenPriority::HelpScreens, &m_ContextTable\n            ,  L"HelpScreens.mercury");'
>>> pattern = re.compile(r'm_pMainSceneManager->PushScene<ConfigurationSpecificHelpScreens>\(.*?\)', flags=re.DOTALL)
>>> pattern.match(s)
<_sre.SRE_Match object at 0x02DE2AA0>

相关问题 更多 >