我有这个链接:
http://www.mySite.come/part1/one-two-12/one-two-three-four-x36-250g-P469198/
如果最后一部分以'P'开头并且数字如:P432432
,我想要谢谢我怎么能爆炸并检查我的病情?
我试过了:
url="http://www.mySite.come/part1/one-two-12/one-two-three-four-x36-250g-P469198/"
url.s.split('-')
答案 0 :(得分:2)
您可以使用-P\d+/?$
正则表达式:
>>> import re
>>> url = "http://www.mySite.come/part1/one-two-12/one-two-three-four-x36-250g-P469198/"
>>> re.search(r"-P\d+/?$", url)
<_sre.SRE_Match object at 0x104faf920>
说明:
-P
是一个短划线,后跟P
,字面意思\d+
会匹配一个或多个数字/?
可选择匹配斜杠(考虑到它可能并不总是存在)$
将匹配字符串的结尾如果要提取该部分,请使用捕获组:
>>> match = re.search(r"-(P\d+)/?$", url)
>>> match.group(1)
'P469198'
答案 1 :(得分:1)
您可以使用
re.sub("[^\w]", "" , url.split('-')[-1])
获取最后一部分并使用
进行验证re.match("P\d+", re.sub("[^\w]", "", url.split('-')[-1]))
或
re.search("P\d+", re.sub("[^\w]", "", url.split('-')[-1]))
答案 2 :(得分:1)
如果您只是需要检查最后一部分是否包含var input = @"Jesus said, ""'Love your neighbor as yourself.'
There is no commandment greater than these"" (Mark 12:31).";
var bibleQuotesRegex =
@"(?<quote>"".+"") # a series of any characters in quotes
\s + # followed by spaces
\( # followed by a parenthetical expression
(?<book>\d*[a-z.\s] *) # book name (a-z, . or space) optionally preceded by digits. e.g. '1 Cor.'
(?<chapter>\d+) # chapter e.g. the '1' in 1:2
: # semicolon
(?<verse>\d+) # verse e.g. the '2' in 1:2
\)";
foreach(Match match in Regex.Matches(input, bibleQuotesRegex, RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.IgnoreCase))
{
var bibleQuote = new
{
Quote = match.Groups["quote"].Value,
Book = match.Groups["book"].Value,
Chapter = int.Parse(match.Groups["chapter"].Value),
Verse = int.Parse(match.Groups["verse"].Value)
};
//do something with it.
}
,您可以使用:
-Pdigit
if re.search(r"-P\d+/$", subject, re.DOTALL):
# Successful match
else:
# Match attempt failed