首页 > 解决方案 > 带有空间字符串的 Python 正则表达式

问题描述

我有一个程序需要使用正则表达式查找网络名称。网络将采用以下形式:“ASCII ASCII”后跟一个\r\n

我需要包括空间,但不能有任何\ror \n。我的问题是我必须使用re,而 usingre.search不适用于\ror \n

我有

re.search("(?:Profile\s*:\s)(.*\s)", networks)

这给了我一切,直到空间,和

re.search("(?:Profile\s*:\s)(.*)", networks)

这给了我列表中的所有内容。

每次我尝试做

re.search("(?:Profile\s*:\s)(.*)(\r|\n)", networks)

或类似的东西,返回的字符串为 NULL。

我怎样才能做到这一点?

编辑:

网络是:

b'\r\nProfiles on interface Wi-Fi:\r\n\r\nGroup policy profiles (read only)\r\n---------------------------------\r\n    <None>\r\n\r\nUser profiles\r\n-------------\r\n    All User Profile     : NAME 2.4\r\n\r\n'

标签: pythonregex

解决方案


你需要一个非贪婪的匹配,否则\r当你使用时捕获也会得到(\r|\n)

import re

networks = b'\r\nProfiles on interface Wi-Fi:\r\n\r\nGroup policy profiles (read only)\r\n---------------------------------\r\n    <None>\r\n\r\nUser profiles\r\n-------------\r\n    All User Profile     : NAME 2.4\r\n\r\n'
m = re.search(rb'Profile\s+:\s+(.*?)(?:\r|\n)',networks)
if m:
    print(m.group(1))

输出:

b'NAME 2.4'

推荐阅读