[英]Python -- Regex match pattern OR end of string
import re
re.findall("(\+?1?[ -.]?\(?\d{3}\)?[ -.]?\d{3}[ -.]?\d{4})(?:[ <$])", "+1.222.222.2222<")
如果我的字符串以“<”或空格結尾,則上面的代碼可以正常工作。 但如果它是字符串的結尾,它就不起作用。 在這種情況下如何讓 +1.222.222.2222 返回:
import re
re.findall("(\+?1?[ -.]?\(?\d{3}\)?[ -.]?\d{3}[ -.]?\d{4})(?:[ <$])", "+1.222.222.2222")
*我刪除了“<”並終止了字符串。 在這種情況下,它不返回任何內容。 但我希望它返回完整的字符串——+1.222.222.2222
可能的答案:
import re
re.findall("(\+?1?[ -.]?\(?\d{3}\)?[ -.]?\d{3}[ -.]?\d{4})(?:[ <]|$)", "+1.222.222.2222")
我認為您已經解決了字符串結尾問題,但是您的問題中的模式還有一些其他潛在問題:
-
[ -.]
中的 - 需要轉義為\-
或放在方括號內的第一個或最后一個 position 中,例如[-. ]
[-. ]
或[.-]
; 如果您在此處的文檔中搜索[]
,您將找到相關信息:Ranges of characters can be indicated by giving two characters and separating them
by a '-', for example [a-z] will match any lowercase ASCII letter, [0-5][0-9] will match
all the two-digits numbers from 00 to 59, and [0-9A-Fa-f] will match any hexadecimal
digit. If - is escaped (e.g. [a\-z]) or if it’s placed as the first or last character
(e.g. [-a] or [a-]), it will match a literal '-'.
(?:\(\d{3}\)?|\d{3}[-. ]?)
這是包含上述內容的可能調整
import re
pat = "^((?:\+1[-. ]?|1[-. ]?)?(?:\(\d{3}\) ?|\d{3}[-. ]?)\d{3}[-. ]?\d{4})(?:[ <]|$)"
print( re.findall(pat, "+1.222.222.2222") )
print( re.findall(pat, "+1(222)222.2222") )
print( re.findall(pat, "+1(222.222.2222") )
Output:
['+1.222.222.2222']
['+1(222)222.2222']
[]
也許嘗試:
import re
re.findall("(\+?1?[ -.]?\(?\d{3}\)?[ -.]?\d{3}[ -.]?\d{4})(?:| |<|$)", "+1.222.222.2222")
null
匹配任何 position, +1.222.222.2222
匹配空格字符, +1.222.222.2222
<
匹配小於號字符, +1.222.222.2222<
$
行尾, +1.222.222.2222
您還可以使用regex101來簡化調試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.