regex 针对特定模式的Python字符串检查

juud5qan  于 2023-04-22  发布在  Python
关注(0)|答案(2)|浏览(161)

我的要求是,如果字符串与单词“develop”或“develop[-9]”匹配,我希望打印true

import re
    
# Target String one
str  = ["develop","develop1","develop123","developtest","develop9_test"]
    
# pattern to find three consecutive digits
# compile string pattern to re.Pattern object
for i in range(0, len(str)):
    if re.match(r"develop\d", str[i]):
        print("true")

我只想打印字符串“develop”,“develop 1”,和“develop 123”的true。任何帮助是感激的?上面的代码也得到了语法问题,我不知道如何解决它?

utugiqy6

utugiqy61#

错误原因是缩进错误,您忘记了在最后一行之前的缩进块。在Python中,缩进不是可选的!
此外,要匹配develop之后的任意位数(包括0),您应该在\d之后添加*,以表示出现零次或更多次。
最后,您应该使用re.fullmatch而不是re.match来匹配整个字符串,而不仅仅是开头。

import re

# Target String one
str = ["develop","develop1","develop123","developtest","develop9_test"]

# pattern to find three consecutive digits
# compile string pattern to re.Pattern object
for i in range(0, len(str)):
  if re.fullmatch(r"develop\d*", str[i]):
    print("true")
xdnvmnnf

xdnvmnnf2#

要检查特定Patten中的字符串,请执行以下操作:

import re

# Target String one
str_list = ["develop","develop1","develop123","developtest","develop9_test"]

# pattern to find three consecutive digits
pattern = r"develop\d{3}"

# compile string pattern to re.Pattern object
regex = re.compile(pattern)

for s in str_list:
    if regex.search(s):
        print(f"'{s}' matches the pattern '{pattern}'")
    else:
        print(f"'{s}' does not match the pattern '{pattern}'")

相关问题