簡體   English   中英

如何使用正則表達式在字符串中查找單詞的“片斷”並在python中使用它?

[英]How to find a “piece” of word in a string with regex and using it in python?

為了進行假期作業,在密碼檢查python程序中,我想使用正則表達式來查找用戶提供的密碼中是否包含用戶的名稱(或名稱的“ piece”, 即2個連續字母 ) 。

第1部分:正則表達式本身

假設用戶名為Samuel

  • 匹配的密碼:

    \n 塞繆爾\n sAm123\n 123Sam\n lSAMUo\n SA\n
  • 密碼不匹配:

    \n S3M\n leumas\n SML\n S123\n

到目前為止,我僅成功完成了此不完整的正則表達式:

[sS]?[aA]?[mM]?[uU]?[eE]?[lL]?

但是,如果密碼中只有一個來自正則表達式的字母,並且不是連續的2個字母,它也會匹配。

如何增強正則表達式?

第2部分:Python使用

當我使用re包中的search功能時,只有在字符串開始時,它才與我以前的正則表達式匹配。 這是一個應該起作用的案例的示例代碼:

import re
reg = r"[sS]?[aA]?[mM]?[uU]?[eE]?[lL]?"
re.match(reg, "samuel")  # Match
re.match(reg, "sml")  # Match
re.match(reg, "123sam")  # Doesn't match
re.match(reg, "zzzSAmu")  # Doesn't match

我想念什么?

你可以試試:

import re

pattern = r"(?i)sa|am|mu|ue|el"
for _string in ("samuel", "sAm123", "1235Sam", "lSAMUo", "sa"):
    assert re.search(pattern, _string) is not None

for _string in ("s3m", "leumas", "sml", "s123"):
    assert re.search(pattern, _string) is None

這里的主要內容是:

  • 文檔所述,使用re.search()而不是re.match()

    如果要在字符串中的任意位置找到匹配項,請改用search()(另請參見search()vs. match())。

  • (?i)使正則表達式不區分大小寫

感謝@sin建議在問題注釋中使用成對字符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM