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 )
1
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) |
3
ipwx 2019-07-09 10:34:34 +08:00
|
5
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: ... |
7
ipwx 2019-07-09 23:24:54 +08:00
|
8
ipwx 2019-07-09 23:27:10 +08:00
|
9
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 |