[英]How to find a pattern in a string
在字符串中找到模式位置時卡住了。 該字符串由6個字符組成, 僅由大寫字母(AZ)或數字(0-9)組成 。
check_string = 'I have a string 09A4N5'
我必須找到'09A4N5'的位置,它可以是類似格式的任何其他字符串。 我嘗試使用正則表達式,並且能夠找到下面提到的解決方案,它給出了“字符串”這個詞的位置。
re.search('\w+\w+\w+\w+\w+\w',check_string).start()
9
你可以用
m = re.search(r'\b[A-Z0-9]{6}\b', check_string)
if m:
print(m.group()) # => 09A4N5
print(m.start(0)) # => 16
圖案細節
\\b
- 單詞邊界
[A-Z0-9]
- 大寫的ASCII字母或數字 {6}
- 正好六次 \\b
- 單詞邊界。 如果要在正則表達式中要求至少一個數字和至少一個大寫字母,請使用
r'\b(?=[A-Z]*\d)(?=\d*[A-Z])[A-Z0-9]{6}\b'
請參閱正則表達式演示 。 這里,
(?=[AZ]*\\d)
- 至少需要一位數 (?=\\d*[AZ])
- 至少需要一個大寫字母 編輯:剛剛看到它總是六個字符。
您想要搜索AZ
或0-9
及其組合。 使用[..]
您可以定義一個字符集:
re.findall(r"[A-Z0-9]{6}", check_string)
{6}
說,你想要6個字符。 通過search
找到該位置:
res = re.search(r"[A-Z0-9]{6}", check_string)
res.span()
check_string = 'I have a string 09A4N5'
for i, x in enumerate(check_string.split()):
if len(x) < 6 or any([ i.islower() for i in x ]):
continue
else:
idx = check_string.index(x)
match = x
print('position:', idx, '- string:', match)
# position: 16 - string: 09A4N5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.