如何在工作簿中查找包含类似于 'TK005' 的字符串的所有单元格?

How to find all cells in a work book that contain strings that look like 'TK005'?

请注意,字符串的前两个字母可以是任意两个字母的集合,但字符串的最后一个字符始终是数字。

for row in ws.iter_rows():
    for cell in row:
        if str(cell.value) == #something like 'XX008':
            print(cell.value)
import re
for row in ws.iter_rows():
    for cell in row:
        if re.search('\w\w\d\d\d', cell.value):
            print(cell.value)

这应该有效。如果你愿意,你也可以压缩 '\w\w\d\d\d' 字符串,但如果你知道你的字符串总是 2 个单词字符后跟 3 个数字,那么你就很好了。

编辑: 既然我有时间,我不妨向您展示一个更好的正则表达式字符串。

'[a-zA-Z]{2}\d{3}'

这个正则表达式字符串比我最初给你的那个还要好。 \w 是正则表达式字符串中的一个特殊字符,它将匹配任何单词字符。这意味着 [a-zA-Z0-9] \d 将只匹配 [0-9]。为了更具体,我指定了一个仅包含字母字符的范围来代替 \w.

至于 {2} 和 {3},它的意思是 "match me 2 of the characters/range of characters that precede" 所以您将得到 2 个字符 A-Z 或 a-z 后跟 3 位数字 0-9。