W1ND123 发表于 2021-11-27 10:29:26

关于正则表达的问题


问题1:是哪里打错了呢,既然报错了
import re
re.search(r'(({0,1}\d{0,1}\d|2\d|25\.){3}({0,1}\d{0,1}\d|2\d|25)', 'other192.168.1.1other')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
    re.search(r'(({0,1}\d{0,1}\d|2\d|25\.){3}({0,1}\d{0,1}\d|2\d|25)', 'other192.168.1.1other')
File "E:\pyhthon\lib\re.py", line 201, in search
    return _compile(pattern, flags).search(string)
File "E:\pyhthon\lib\re.py", line 304, in _compile
    p = sre_compile.compile(pattern, flags)
File "E:\pyhthon\lib\sre_compile.py", line 764, in compile
    p = sre_parse.parse(p, flags)
File "E:\pyhthon\lib\sre_parse.py", line 948, in parse
    p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
File "E:\pyhthon\lib\sre_parse.py", line 443, in _parse_sub
    itemsappend(_parse(source, state, verbose, nested + 1,
File "E:\pyhthon\lib\sre_parse.py", line 836, in _parse
    raise source.error("missing ), unterminated subpattern",
re.error: missing ), unterminated subpattern at position 0

问题2:红色是一个小组,那绿色的哪个小括号是干嘛的
re.search(r'(({0,1}\d{0,1}\d|2\d|25\.){3}({0,1}\d{0,1}\d|2\d|25)', 'other192.168.1.1other')

君无泪 发表于 2021-11-27 11:19:36

# 这样可以匹配 192.168.1.1
import re
patterm = '{1,3}\.{1,3}\.{1,3}\.{1,3}'
string = 'other192.168.1.1other'

print(re.search(patterm, string))

wp231957 发表于 2021-11-27 11:20:40

缺括号吧

xugh123 发表于 2021-11-27 15:21:52

r"(??+.){3}??+"

W1ND123 发表于 2021-11-27 16:25:58

wp231957 发表于 2021-11-27 11:20
缺括号吧

没有呀,和小甲鱼的一模一样

txxcat 发表于 2021-11-27 16:49:06

提示很清楚了,差一个右括号。
re.search(r'(({0,1}\d{0,1}\d|2\d|25)\.){3}({0,1}\d{0,1}\d|2\d|25)', 'other192.168.1.1other')

W1ND123 发表于 2021-11-28 10:03:50

txxcat 发表于 2021-11-27 16:49
提示很清楚了,差一个右括号。
re.search(r'(({0,1}\d{0,1}\d|2\d|25)\.){3}({0,1}\d{0 ...

re.search(r'({0,1}\d{0,1}\d|2\d|25\.){3}({0,1}\d{0,1}\d|2\d|25)', 'other192.168.1.1other')

这样子不是也可以代表红色小组重复三次嘛?
为什么要多一组括号呢,谢谢回答!

suchocolate 发表于 2021-11-28 11:33:03

W1ND123 发表于 2021-11-28 10:03
re.search(r'({0,1}\d{0,1}\d|2\d|25\.){3}({0,1}\d{0,1}\d|2\d|25)', 'oth ...

abc{3}# 只能匹配3个重复的c,即abccc
(abc){3}# abc成为一组,可以匹配3组abc,即abcabcabc
基本功先练好,事半功倍。https://www.runoob.com/python3/python3-reg-expressions.html
页: [1]
查看完整版本: 关于正则表达的问题