[英]how to get part of string by regular expression in python
我想通過正則表達式獲取字符串的一部分,但我嘗試這樣做,但返回的值超出了我的需要。 這是我的代碼:
Release_name = 'My Kitchen Rules S10E35 720p HDTV x264-ORENJI'
def get_rls(t):
w = re.match(".*\d ", t)
if not w: raise Exception("Error For Regular Expression")
return w.group(0)
regular_case = [Release_name]
for w in regular_case:
Regular_part = get_rls(w)
print(">>>> Regular Part: ", Regular_part)
此示例的代碼“ My Kitchen Rules S10E35 720p HDTV x264-ORENJI
”返回此“ My Kitchen Rules S10E35
”,但我不需要“ S10E35
”,只需返回此My Kitchen Rules
您可以使用
w = re.match(r"(.*?)\s+S\d+E\d+", t)
並且由於您需要的價值在第1組:
return w.group(1)
參見Python演示 ,輸出為>>>> Regular Part: My Kitchen Rules
。
圖案細節
(.*?)
-除換行符以外的任何0+個字符,請盡可能少 \\s+
-1+空格 S\\d+E\\d+
S
字符,1個以上數字, E
和1個以上數字 re.match
僅從字符串的開頭開始匹配,不需要在模式開頭的^
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.