python - 带有空间字符串的 Python 正则表达式
问题描述
我有一个程序需要使用正则表达式查找网络名称。网络将采用以下形式:“ASCII ASCII”后跟一个\r
或\n
。
我需要包括空间,但不能有任何\r
or \n
。我的问题是我必须使用re
,而 usingre.search
不适用于\r
or \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'
解决方案
你需要一个非贪婪的匹配,否则\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'
推荐阅读
- json - 如何从 JSON 对象获取数据到 Angular?
- c - 如何用前导零填充整数打印?
- angularjs - ng-options 如何在没有控制器的情况下工作?
- javascript - Internet Explorer 8 - 新 Map() 替换
- python-3.x - SelectKBest 将分数作为 nan 值
- python - 从字典到列表的日期
- reactjs - Model.confirm () 不允许使用“This”
- c - 如何调试从 Go 代码到 C 代码的调用中的 memleak?
- entity-framework-core - 如何使用 Entity Framework Core 2 中的每层次表 (TPH) 模式将列保存为 json
- javascript - 从变量 React-Native 将数据膨胀到 FlatList