简体   繁体   中英

how to get part of string by regular expression in python

I want to get part of string by regular expression I try this but it returns more than I need. This my code :

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)

This code for this example " My Kitchen Rules S10E35 720p HDTV x264-ORENJI " return this " My Kitchen Rules S10E35 " but i do not need the " S10E35 " just return this My Kitchen Rules

You may use

w = re.match(r"(.*?)\s+S\d+E\d+", t)

and since the value you need is in Group 1:

return w.group(1)

See the Python demo , output is >>>> Regular Part: My Kitchen Rules .

Pattern details

  • (.*?) - any 0+ chars other than line break chars, as few as possible
  • \\s+ - 1+ whitespaces
  • S\\d+E\\d+ - S char, 1+ digits, E and 1+ digits

The re.match will only start matching from the start of the string, ^ at the start of the pattern is not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM