Python 正则表达式合并的问题

2019-07-09 09:50:13 +08:00
 ladypxy

pattern = re.compile(r'port (\d+)') pattern1 = re.compile(r'Logon ID:\t\t(\w+)\r\n\tLogon')

怎么写才能把这 2 个合并到一起然后返回 ()即 \d+ \w+中的匹配呢? 分开写匹配正常

试着如果写成

pattern = re.compile(r'port (\d+)|Logon ID:\t\t(\w+)\r\n\tLogon')

这样会匹配不到返回 none

而如果写成

pattern = re.compile(r'( port (\d+))|( Logon ID:\t\t(\w+)\r\n\tLogon )')

这样返回的又是 整个括号中的字段,port (\d+)或者 Logon ID:\t\t(\w+)\r\n\tLogon )

2615 次点击
所在节点    Python
10 条回复
bomb77
2019-07-09 10:19:01 +08:00
In [3]: re.compile(r'port(\d+)|Logon ID(\d+)')
Out[3]: re.compile(r'port(\d+)|Logon ID(\d+)')

In [4]: p1 = re.compile(r'port(\d+)|Logon ID(\d+)')

In [5]: p1.match('Logon ID8Logon')
Out[5]: <_sre.SRE_Match at 0x1099fee00>

In [6]: m = p1.match('Logon ID8Logon')

In [7]: m.groups()
Out[7]: (None, '8')

In [8]: m
Out[8]: <_sre.SRE_Match at 0x109e43030>

In [9]: m2 = p1.match('port5')

In [10]: m2
Out[10]: <_sre.SRE_Match at 0x109e430b8>

In [11]: m2.groups()
Out[11]: ('5', None)
bomb77
2019-07-09 10:21:48 +08:00
@bomb77 #1 应该都能匹配出来的,只是匹配到的结果在 groups 的不同 index 里吧
ipwx
2019-07-09 10:34:34 +08:00
用 ?: ?P 和 groupdict()

http://ideone.com/qFhwVd
ladypxy
2019-07-09 12:36:37 +08:00
@ipwx 多谢
请问如果不想返回 dict,只想获取 id,能做到么
ipwx
2019-07-09 16:25:13 +08:00
@ladypxy 你都拿到 dict 了想怎么办就怎么办呗。

if xxx.groupdict()['id'] is not None:
...
elif xxx.groupdict()['port'] is not None:
...
ladypxy
2019-07-09 16:31:06 +08:00
@ipwx 代码字节数有限制……所以想尽量一次搞定啊
ipwx
2019-07-09 23:24:54 +08:00
ipwx
2019-07-09 23:27:10 +08:00
2gua
2019-07-11 12:07:53 +08:00
from typing import Optional, Match, Pattern, Tuple
import re


def matchs(target: str) -> Optional[str]:
pat: Pattern[str] = re.compile(r"port\s*(\d+)|Logon ID:\s*(\w+)")
res: Optional[Match[str]] = re.search(pat, target)
if res:
g: Tuple[Optional[str], Optional[str]] = res.groups()
return g[0] if g[0] else g[1]
return None
ladypxy
2019-07-17 08:24:45 +08:00
@livid, 帮忙删除下这个帖子,没注意泄漏了不少信息。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/581211

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX